SortedLists come in handy when developers need to maintain a collection of objects that is sorted every time an item is added or removed. In this tip, I look at a way of implementing and utilizing SortedLists in VB.NET.
Advantages and disadvantages of using a SortedList
System.Collections.SortedList type is a key-based dictionary type that allows you to store items in an ordered manner. This is advantageous whenever you need to be able to store sorted data without going through a separate routine of sorting the contents of a collection. The convenience of a SortedList comes at the price of slower additions and removals of items to the list. A SortedList utilizes two arrays internally: one array stores keys, while another stores the data or object reference.
When you work with SortedLists in VB.NET, keep in mind that objects are sorted based on the key value and not an object itself; therefore, the key needs to be a type that supports IComparable—either an integer or a string. Otherwise, you have to create a custom IComparer as an argument to the SortedList when defining the SortedList.
In the Listing A code sample, I define a new instance of a SortedList class, srtList. I also define an item as a DictionaryEntry in order to hold a particular entry at a time that will be stored in the SortedList. Then I add three items to the list utilizing its Add method.
Notice that I add items a, b, c, but the keys are 1, 3, 2. This is on purpose to demonstrate two things: The items will be sorted in the SortedList right away, and the items will be sorted based on their keys. To confirm this, I create a loop to go through all items in the srtList and display their key and value pairs one-by-one. As expected, the order in which the items appear are as follows: Key: 1; Value: a; Key :2; Value:c, Key: 3; Value: b.
Miss a tip?
Advance your scripting skills to the next level with TechRepublic's free Visual Basic newsletter, delivered each Friday. Automatically sign up today!