Sorting a dictionary based on key in C# : SortedDictionary

For a long time I have been trying to sort the contents of a dictionary. I had to copy the contents to an array for sorting the contents which makes the code lengthy and dirty. But now I happened to hear about SortedDictionay. Sorted dictionary sorts the elements based on the key. An example is given below.


SortedDictionary<int, string> dict = new SortedDictionary<int, string>();
dict.Add(90, "First");
dict.Add(0, "Second");
dict.Add(2, "Third");
dict.Add(100, "Fourth");
dict.Add(22, "Fifth");
dict.Add(12, "Sixth");
dict.Add(7, "Seventh");
foreach(KeyValuePair<int,string> i in dict)
{
     Console.WriteLine(i.Key+" : "+ i.Value);
}

Output

 0 : Second

 2 : Third
 7 : Seventh
 12 : Sixth
 22 : Fifth
 90 : First
 100 : Fourth


You can also use SortedList for the same purpose. SortedList uses less memory than SortedDictionary but it is slower than SortedDictionary.

Comments