The SortedList collection is a combination of the Array and HashTable classes. It maintains a list of items that can be accessed either with an index or with a key. When you access items by their indices, the SortedList behaves just like an ArrayList; when you access items by their keys, the SortedList behaves like a HashTable. What’s unique about the SortedList is that this collection is always sorted according to the keys. The items of a SortedList are always 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 such as the following:
Dim sList As New SortedListCode language: PHP (php)
As you might 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, where comparer is the name of a custom class that implements the IComparer interface (which is discussed in detail later in this chapter):
Dim sList As New SortedList(New comparer)Code language: PHP (php)
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 automatically 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 the following, where key is the key of the new item and item is the item to be added:
sList.Add(key, item)Code language: CSS (css)
Both arguments are objects. But remember, if the keys are objects, the collection won’t be automatically sorted; you must provide your own comparer, as discussed later in this chapter. The Add method is the only way to add items to a SortedList collection, and all keys must be unique; attempting to add a duplicate key will throw an exception.
The SortedList class also exposes the ContainsKey and ContainsValue methods, which allow you to find out whether a key or item already exists in the list. To add a new item, use the following statement to make sure that the key isn’t in use:
If Not sList.ContainsKey(myKey) Then sList.Add(myKey, myItem) End IfCode language: CSS (css)
It’s okay to store duplicate values in the same SortedList collection, but you can still detect the presence of an item in the list via 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 the following, 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:
sList.SetByIndex(index, item)Code language: CSS (css)
This object will replace the value that corresponds to the specified index. 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 an argument and removes the item that corresponds to that key. The RemoveAt method accepts an index as an 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).
The SortedList Example
Let’s build a SortedList and print out its elements (this section’s sample project is the SortedList Example – Download the example here). Listing 10.9 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. However, 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, the Show Keys and Values button, and enter the statements of Listing 10.9 in its Click event handler.
Listing 10.9: Populating a Simple SortedList
Private Sub bttnShow_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button1.Click Dim sList As New System.Collections.SortedList sList.Add(116, "item 3") sList.Add(110, "item 9") sList.Add(115, "item 4") sList.Add(217, "item 2") sList.Add(211, "item 8") sList.Add(214, "item 5") sList.Add(318, "item 1") sList.Add(312, "item 7") sList.Add(319, "item 0") sList.Add(313, "item 6") Dim SLEnum As IDictionaryEnumerator SLEnum = sList.GetEnumerator() ListBox1.Items.Clear() ListBox1.Items.Add("The HashTable's Keys and Values") While SLEnum.MoveNext ListBox1.Items.Add("Key = " & SLEnum.Key.ToString & ", Value= " & _ SLEnum.Value.ToString) End While ListBox1.Items.Add("The HashTable's Values by Index") Dim idx As Integer For idx = 0 To sList.Count - 1 ListBox1.Items.Add("Item " & sList.GetByIndex(idx).ToString & _ " is at location " & sList.IndexOfValue(sList.GetByIndex(idx)).ToString) Next ListBox1.Items.Add("The HashTable's Keys by Index") For idx = 0 To sList.Count - 1 ListBox1.Items.Add("The key at location " & idx.ToString & " is " & _ sList.GetKey(idx).ToString) Next End SubCode language: PHP (php)
The first segment of the code populates the collection, and 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 = 110, Value= item 9 Key = 115, Value= item 4 Key = 116, Value= item 3 Key = 211, Value= item 8 Key = 214, Value= item 5 Key = 217, Value= item 2 Key = 312, Value= item 7 Key = 313, Value= item 6 Key = 318, Value= item 1 Key = 319, Value= item 0
The items are sorted according to their keys, regardless of the order in which they were inserted into the collection.