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

504 Chapter 11 STORING DATA IN COLLECTIONS

The SortedList Class

The SortedList collection is a peculiar combination of the Array and HashTable classes. It maintains a list of items, which can be accessed either with an index or with a key. Moreover, the collection is always sorted according to the keys. The items of a SortedList are ordered according to the values of their keys, and there’s no method for sorting the collection according to the values stored in it.

To create a new SortedList collection, use a statement like the following:

Dim sList As New SortedList

As you may have guessed, this collection can store keys that are of the base data types. If you want to use custom objects as keys, you must specify an argument of the IComparer type, which tells VB how to compare the custom items. This information is crucial; without it, the SortedList won’t be able to maintain its items sorted. You can still store items in the SortedList, but they will appear in the order in which they were added.

This form of the SortedList constructor has the following syntax:

Dim sList As New SortedList(New comparer)

where comparer is the name of a custom IComparer interface (which is discussed in detail later in this chapter). There are also two more forms of the constructor, which allow you to specify the initial capacity of the SortedList collection, as well as a Dictionary object, whose data (keys and values) will be added to the SortedList.

Like the other two collections examined in this chapter, the SortedList collection supports the Capacity and Count properties. To add an item to a SortedList collection, use the Add method, whose syntax is

sList.Add(key, item)

where key is the key of the new item and item is the item to be added. Both arguments are objects. The Add method is the only way to add items to a SortedList collection. All items are inserted into the collection according to their keys, and each item’s key must be unique. Attempting to add a duplicate key will throw an exception.

The SortedList class also exposes the ContainsKey and ContainsValue properties, which allow you to find out whether a key or item exists in the list already. To add a new item, use the following statement that makes sure the key isn’t in use:

If Not sList.ContainsKey(myKey) Then

sList.Add(myKey, myItem)

End If

(Just replace myKey and myItem with your key and item.) It’s OK to store duplicate items in the same SortedList collection, but you can still detect the presence of an item in the list with a similar If statement.

To replace an existing item, use the SetByIndex method, which replaces the value at a specific index. The syntax of the method is

sList.SetByIndex(index, item)

where the first argument is the index at which the value will be inserted and item is the new item to be inserted in the collection. This object will replace the value that corresponds to the specified index.

Copyright ©2002 SYBEX, Inc., Alameda, CA

www.sybex.com

THE SORTEDLIST CLASS 505

The key, however, remains the same. There’s no equivalent method for replacing a key; you must first remove the item, and then insert it again with its new key.

To remove items from the collection, use the Remove and RemoveAt methods. The Remove method accepts a key as argument and removes the item that corresponds to that key. The RemoveAt method accepts an index as argument and removes the item at the specified index. To remove all the items from a SortedList collection, call its Clear method. After clearing the collection, you should also call its TrimToSize method to restore its capacity to the default size (16).

Let’s build a SortedList and print out its elements. The following listing declares the sList SortedList and then adds 10 items to the collection. The keys are integers, and the values are strings. The items are added in no specific order, but as soon as they’re added they’re inserted at the proper location in the collection, so that their keys are in ascending order.

Create a new project, place a button on its form, and enter Listing 11.11 in its Click event handler. The project you’ll build in this section is called SortedList, and you can find it on the CD.

Listing 11.11: Populating a Simple SortedList

Public Sub Button1_Click(ByVal sender As System.Object, _

ByVal e As System.EventArgs)

Dim sList As New System.Collections.SortedList()

Populate sortedlist sList.Add(16, “item 3”) sList.Add(10, “item 9”) sList.Add(15, “item 4”) sList.Add(17, “item 2”) sList.Add(11, “item 8”) sList.Add(14, “item 5”) sList.Add(18, “item 1”) sList.Add(12, “item 7”) sList.Add(19, “item 0”) sList.Add(13, “item 6”)

Dim SLEnum As IDictionaryEnumerator SLEnum = sList.GetEnumerator()

Print all key-value pairs While SLEnum.MoveNext

Console.WriteLine(“Key = “ & SLEnum.Key.Tostring & “, Value= “ & _

SLEnum.Value.ToString

End While

End Sub

The first segment of the code populates the ArrayList, while the second segment of the code prints all the key–value pairs in the order in which the enumerator retrieves them. The enumerator is the built-in mechanism for scanning a collection’s items (it will be discussed in detail later in this chapter).

If you execute these statements, they will produce the following output:

Key = 10, Value= item 9

Key = 11, Value= item 8

Copyright ©2002 SYBEX, Inc., Alameda, CA

www.sybex.com

506 Chapter 11 STORING DATA IN COLLECTIONS

Key = 12, Value= item 7

Key = 13, Value= item 6

Key = 14, Value= item 5

Key = 15, Value= item 4

Key = 16, Value= item 3

Key = 17, Value= item 2

Key = 18, Value= item 1

Key = 19, Value= item 0

The items are sorted according to their keys, regardless of the order in which they were inserted into the collection.

Let’s look now at a few methods for extracting keys and values. To find out the index of a value in the SortedList, use the IndexOfValue method, which accepts as argument an object. If the object exists in the collection, it returns its index. If not, it returns the value –1. If the same value appears more than once in the collection, the IndexOfValue property will return the first instance of the value. Moreover, there’s no mechanism for retrieving the following instances. Notice that the IndexOfValue property performs a case-sensitive search. The following statement will return the index 2 (the item you’re looking for is in the third place in the original SortedList):

Console.WriteLine(sList.IndexOfValue(“item 7”))

You can also find out the index of a specific key, with the IndexOfKey method, whose syntax is similar. Instead of a value, it locates a key. The following statement will return the index 7 (the key you’re looking for is in the eighth place in the SortedList):

Console.WriteLine(sList.IndexOfKey(17))

The GetKey and GetValue methods allow you to retrieve the index that corresponds to a specific key or value in the SortedList. Both methods accept an object as argument and return an index.

Finally, you can combine the two methods to retrieve the key that corresponds to a value, with a statement like the following one:

Console.WriteLine(sList.GetKey(sList.IndexOfValue(“item 7”)))

This statement will print the value 12, based on the contents of the sList collection in Listing 11.11.

Note If either the key or the value you’re searching for can’t be found, the IndexOfKey and IndexOfValue methods will return –1.

You can retrieve the keys in a SortedList collection and create another list, with the GetKeyList method. Likewise, the GetValueList method returns all the values in the SortedList. The following code extracts the keys from the sList SortedList and stores them in the keys list. Then, it scans the list with the help of the key variable and prints all the keys:

Dim keys As IList

keys = slist.GetKeyList() Dim key As Integer

For Each key In Keys Console.WriteLine(key)

Next

Copyright ©2002 SYBEX, Inc., Alameda, CA

www.sybex.com

THE SORTEDLIST CLASS 507

You can also extract both the keys and the values from a SortedList and store them into an ArrayList, as shown here:

Dim AllKeys As New ArrayList()

AllKeys.InsertRange(0, sList.GetValueList)

Each item is stored at a specific location in the SortedList, and you can find out the location of each item with a loop like the following:

Dim idx As Integer

For idx = 0 To sList.Count - 1

Console.WriteLine(“ITEM: “ & sList.GetByIndex(idx).ToString & _ “ is at location “ & idx.Tostring)

Next

The output produced by this code segment is:

ITEM: item 9 is at location 0

ITEM: item 8 is at location 1

ITEM: item 7 is at location 2

ITEM: item 6 is at location 3

ITEM: item 5 is at location 4

ITEM: item 4 is at location 5

ITEM: item 3 is at location 6

ITEM: item 2 is at location 7

ITEM: item 1 is at location 8

ITEM: item 0 is at location 9

You can also find out the location of each key, with a loop like the following one:

For idx = 0 To sList.Count - 1

Console.WriteLine(“The key at location “ & idx.ToString & “ is “ & _ sList.GetKey(idx).ToString)

Next

The output produced by the preceding code segment is:

The key at location 0 is 10

The key at location 1 is 11

The key at location 2 is 12

The key at location 3 is 13

The key at location 4 is 14

The key at location 5 is 15

The key at location 6 is 16

The key at location 7 is 17

The key at location 8 is 18

The key at location 9 is 19

Notice that the keys are rearranged as they’re added to the list, and they’re always physically sorted. As you can understand, the keys must be of a base data type. If not, the SortedList can’t compare the keys and therefore can’t maintain the proper order. To use objects as keys, you must also supply a function custom comparer (a function that knows how to compare two objects). The topic of creating

Copyright ©2002 SYBEX, Inc., Alameda, CA

www.sybex.com