Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
(ebook) Visual Studio .NET Mastering Visual Basic.pdf
Скачиваний:
120
Добавлен:
17.08.2013
Размер:
15.38 Mб
Скачать

480 Chapter 11 STORING DATA IN COLLECTIONS

VB6 VB.NET

All the topics discussed in this chapter are new to VB.NET. Arrays have been around since the first version of Visual Basic, but all the features discussed in this chapter, such as sorting and searching arrays, are new to VB.NET. ArrayLists are also new to VB.NET; they’re dynamic arrays. Another class, the HashTable, is the evolution of a structure that was known as Dictionary in VB5 and VB6, whose elements are identified not by a number, but by a meaningful key. The basic functionality of the HashTable class is practically identical to that of the Dictionary, but the HashTable has more features, including the ability to sort its elements.

The last topic discussed in this chapter is the ability to specify functions for sorting custom objects in a collection. As you will see, it’s quite simple. These functions don’t actually sort the collection; they simply compare two elements. Once you provide this functionality, the Framework takes it from there and uses your custom functions to sort and search the collection. This type of close interaction with the inner workings of the language is a powerful feature, totally new to VB programmers.

Advanced Array Topics

In Chapter 3, we explored the basics of arrays—how to declare arrays, how to access elements by index, and a few more elementary topics. VB.NET supports arrays through the Array class, which exposes a whole lot of functionality that wasn’t there before. The System.Array class is

not inheritable, which means you can’t create custom arrays; the classes under System.Collections are inheritable, and you can customize the other collections discussed in this chapter.

But before we explore the more advanced methods exposed by the Array class, let me remind you about the basic array members that are new to VB.NET arrays. The Length property returns the number of elements in the array. In the case of a multidimensional array, the Length property returns the total number of elements in all dimensions. To find out the number of dimensions in an array, call its Rank property. The index of the first element in an array is zero, and the index of the last element is retrieved by the method GetUpperBound. If the array is multidimensional, you must specify the dimension whose upper bound you wish to read. The expression array.GetUpperBound(0) returns the upper bound of the first dimension, and the expression array.GetUpperBound(array.Rank - 1) returns the number of elements in the last dimension of the array. For more information on these members, see the section “Arrays” in Chapter 3.

Sorting Arrays

The most prominent feature of the Array class is that VB.NET arrays can be sorted and searched. To sort an array, call its Sort method. This method is heavily overloaded and, as you will see, it is possible to sort an array based on the values of another array, or even supply your own custom sorting routines. If the array is sorted, you can call the BinarySearch method to locate an element. If not, you can call the IndexOf and LastIndexOf methods.

Copyright ©2002 SYBEX, Inc., Alameda, CA

www.sybex.com

ADVANCED ARRAY TOPICS 481

The simplest form of the Sort method accepts a single argument, which is the name of the array to be sorted:

System.Array.Sort(arrayName)

This method sorts the elements of the array according to the type of its elements. If the array is not strictly typed, the Sort method will fail. The Array class just doesn’t know how to compare integers to strings or dates, so don’t attempt to sort arrays whose elements are not of the same type. If you can’t be sure that all elements are of the same type, use a Try…Catch statement.

Note The Sort method is a reference method. It requires that you supply the name of the array to be sorted as an argument, even when you’re applying the Sort method directly to an array. In other words, the expression arrayName.Sort() is invalid. You must still pass the name of the array as argument to the Sort method: arrayName.Sort(arrayName). I’m using the notation System.Array.Sort(arrayName) because it’s easier to understand. Besides, a statement like

names.Sort(names) just isn’t elegant.

You can also sort a section of the array with the following form of the Sort method:

System.Array.Sort(arrayName, startIndex, endIndex)

where startIndex and endIndex are the indices that delimit the section of the array to be sorted. I don’t see what good a half-sorted array can be, unless you’re dealing with extremely large arrays. Even then, the Sort method is incredibly fast.

An interesting variation of the Sort method sorts the elements of an array according to the values of the elements in another array. Let’s say you have one array of names and another with the matching Social Security numbers. It is possible to sort the array with the names according to their Social Security numbers. This form of the Sort method has the following syntax:

System.Array.Sort(array1, array2)

array1 is the array with the keys, and array2 is the array with the actual elements to be sorted. This is a very handy form of the Sort method. Let’s say you have a list of words stored in one array and their frequencies in another. Using the first form of the Sort method, you can sort the words alphabetically. With this form of the Sort method, you can sort them according to their frequencies (starting with the most common words and ending with the less common ones). The two arrays must be one-dimensional and have the same number of elements. If you want to sort a section of the array, just supply the startIndex and endIndex arguments to the Sort method, after the names of the two arrays.

The SortArrayByLength application, shown in Figure 11.1, demonstrates how to sort an array based on the length of its elements (short elements appear at the top of the array, while longer elements appear near the bottom of the array). First, it populates the array MyStrings with a few strings, then it assigns the lengths of these strings to the matching elements of the array MyStringsLen. The element MyStrings(0) is “Visual Basic”, and the MyStringsLen(0) element’s value is 12. Once the two arrays have been populated, the code sorts the elements of the MyStrings array according to the values of the MyStringsLen array.

Copyright ©2002 SYBEX, Inc., Alameda, CA

www.sybex.com

482 Chapter 11 STORING DATA IN COLLECTIONS

Figure 11.1

The SortArray-

ByLength application

The statement that sorts the array is

System.Array.Sort(MyStringsLen, MyStrings)

The code, which also displays the arrays before and after sorting, is shown in Listing 11.1.

Listing 11.1: Sorting an Array According to the Length of Its Elements

Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Dim MyStrings(3) As String

Dim MyStringsLen(3) As Integer

MyStrings(0) = “Visual Basic” MyStrings(1) = “C++” MyStrings(2) = “C#” MyStrings(3) = “HTML”

Dim i As Integer

For i = 0 To UBound(MyStrings) MyStringsLen(i) = len(MyStrings(i))

Next ListBox1.Items.Clear()

ListBox1.Items.Add(“Original Array”) ListBox1.Items.Add(“*************************”) Dim str As Integer

For str = 0 To UBound(MyStrings)

 

ListBox1.Items.Add(MyStrings(str) & “

“ & MyStringsLen(str).ToString)

Next

 

ListBox1.Items.Add(“*************************”)

ListBox1.Items.Add(“Array Sorted According to String Length “)

ListBox1.Items.Add(“*************************”)

System.Array.Sort(MyStringsLen, MyStrings)

 

For str = 0 To UBound(MyStrings)

 

ListBox1.Items.Add(MyStrings(str) & “

“ & MyStringsLen(str).ToString)

Next

 

ListBox1.Items.Add(“*************************”)

Copyright ©2002 SYBEX, Inc., Alameda, CA

www.sybex.com

ADVANCED ARRAY TOPICS 483

Sort the array twice

ListBox1.Items.Add(“Array Sorted Twice According to String Length “) ListBox1.Items.Add(“*************************”) System.Array.Sort(MyStringsLen, MyStrings)

For str = 0 To UBound(MyStrings)

ListBox1.Items.Add(MyStrings(str) & “ “ & MyStringsLen(str).ToString) Next

ListBox1.Items.Add(“*************************”) End Sub

The output produced by the SortArrayByLength application on the ListBox control is shown here:

Original Array

*************************

Visual Basic 12 C++ 3

C# 2

HTML 4

*************************

Array Sorted According to String Length

*************************

C# 2

C++ 3

HTML 4

Visual Basic 12

*************************

Array Sorted Twice According to String Length

*************************

C# 2

C++ 3

HTML 4

Visual Basic 12

*************************

Notice that the Sort method sorts both the auxiliary array (the one with the lengths of the strings) and the main array. After the call to the Sort method, the first element in the MyStrings array is “C#”, and the first element in the MyStringsLen array is 2. In other words, the Sort method doesn’t simply sort the elements of one array based on the values of the other array. If it did, the elements of the two arrays would no longer match. Because of the way the Sort method operates, you can sort the array multiple times, as demonstrated in Listing 11.1.

The array with the keys that will determine the order of the elements can be anything. If the array to be sorted holds some rectangles, you can create an auxiliary array with the area of the rectangles, and sort the original array according to the area of its rectangles. Likewise, an array of colors can be sorted according to the hue, or the luminance, of each color component, and so on.

Copyright ©2002 SYBEX, Inc., Alameda, CA

www.sybex.com