There are times when you need to sort your collection easily. Fortunately, there is a special dictionary called the SortedList to handle these needs. The SortedList is part of the System.Collections.Specialized library (don’t forget your using reference!).
There is one thing to understand that is a bit counter intuitive. The SortedList sorts off of the Key, and not the Value. While this may not seem natural, it can work to your advantage in times when users want to have peculiar sort orders. You can store the odd sort in the key, then display the values to the users.
In my simple example below, I’ve created a SortedList of the artists I might listen to during a day of programming. To make the sort case insensitive, I entered all the keys in lower case, then the value is the artist name in normal type.
SortedList myMusic = new SortedList();
myMusic.Add(“midnight synidicate”, “Midnight Syndicate”);
myMusic.Add(“kate bush”, “Kate Bush”);
myMusic.Add(“clint black”, “Clint Black”);
myMusic.Add(“queen latifah”, “Queen Latifah”);
foreach (DictionaryEntry favoriteArtist in myMusic)
Produces this output in the command window:
When you need to maintain a frequently changing list of values that need to be sorted, using the SortedList dictionary can be a real time saver.
2 thoughts on “Dictionaries in C#: The SortedList”
This is very usefull for key value pairs that has string type value .
But what about integer type values. Can i sort the list by value of type integer instead of string?