Introduction
In my previous article Introduction to Dictionary Collection you learned about the Dictionary collection. If you need to sort the values in the Dictionary a Dictionary cannot be sorted.
Sort Dictionary
There is a one way to sort a Dictionary. We can extract the keys and values then sort those. This is done with keys and values properties and a List instance. Here the List class is used to sort the Dictionary values because there is not a method in Dictionary to sort. If we need the Dictionary contents to be in sorted order, we must acquire the elements and then sort.
Example
In the following example we use the ToList () extension method and Sort () method. These methods are used on the keys.
- using System;
- using System.Collections.Generic;
- using System.Linq;
- namespace Dictionary_Sort
- {
- class Program
- {
- static void Main(string[] args)
- {
-
- var dSort = new Dictionary<int, string>();
- dSort.Add(1, "krishna");
- dSort.Add(2, "Ganesh");
- dSort.Add(5, "Yogesh");
- dSort.Add(4, "Anand");
- dSort.Add(3, "Pranav");
-
- Console.WriteLine("/* Dictionary Before Sorted */");
- foreach (var item in dSort)
- {
- Console.WriteLine("Keys : " + item.Key + " And Values : " + item.Value);
- }
-
-
- var list = dSort.Keys.ToList();
- list.Sort();
- Console.WriteLine();
-
-
- Console.WriteLine("/* Dictionary After Sorted */");
- foreach (var item in list)
- {
- Console.WriteLine("{0} : {1}", item, dSort[item]);
- }
- Console.WriteLine();
- Console.WriteLine("/* Finish */");
- Console.ReadKey();
- }
- }
- }
Output
OrderBy
It is another way to sort a Dictionary. It is the OrderBy extension method in System.Linq. It requires only one Lambda expression and method call.
Example
-
- foreach (var item in dSort.OrderBy(i => i.Value))
- {
- Console.WriteLine(item);
- }
Output
Note: For detailed code please download the Zip file attached above.
Summary
I hope you now understand how to sort a Dictionary. If you have any suggestion regarding this article then please contact me.