Dictionaries in C#: The SortedList

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(“zztop”, “ZZTop”);

      myMusic.Add(“midnight synidicate”, “Midnight Syndicate”);

      myMusic.Add(“kate bush”, “Kate Bush”);

      myMusic.Add(“bond”, “Bond”);

      myMusic.Add(“clint black”, “Clint Black”);

      myMusic.Add(“queen latifah”, “Queen Latifah”);

 

      foreach (DictionaryEntry favoriteArtist in myMusic)

      {

        Console.WriteLine(favoriteArtist.Value);

      }

 

Produces this output in the command window:

Bond
Clint Black
Kate Bush
Midnight Syndicate
Queen Latifah
ZZTop

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.

Advertisement

2 thoughts on “Dictionaries in C#: The SortedList

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s