Learn the pros and cons of working with SortedLists in VB.NET

If you need to maintain a collection of objects that is sorted every time an item is added or removed, consider using VB.NET's SortedLists. In this tip, Irina Medvinskaya outlines the advantages and disadvantages of using a SortedList.

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 IComparableeither 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?

Check out the Visual Basic archive, and catch up on the most recent editions of Irina Medvinskaya's column.

Advance your scripting skills to the next level with TechRepublic's free Visual Basic newsletter, delivered each Friday. Automatically sign up today!

Editor's Picks

Free Newsletters, In your Inbox