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.

About these ads

2 Responses to “Dictionaries in C#: The SortedList”

  1. zülküf küçüközer Says:

    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?

  2. Sort Dictionary by Key « Rainy Days Blog Says:

    [...] Maybe you wonder how you could sort a dictionary by key. I did and I had to search a bit. And I found this: you don’t have to sort. You can just use SortedList and it will do the job for you. Original post and more info here. [...]


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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s

Follow

Get every new post delivered to your Inbox.

Join 93 other followers

%d bloggers like this: