Sort Dictionary in C#

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.

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. namespace Dictionary_Sort  
  5. {  
  6.     class Program  
  7.     {  
  8.         static void Main(string[] args)  
  9.         {  
  10.             // Create a Dictionary and add keys and values  
  11.             var dSort = new Dictionary<intstring>();  
  12.             dSort.Add(1, "krishna");  
  13.             dSort.Add(2, "Ganesh");  
  14.             dSort.Add(5, "Yogesh");  
  15.             dSort.Add(4, "Anand");  
  16.             dSort.Add(3, "Pranav");  
  17.   
  18.            Console.WriteLine("/* Dictionary Before Sorted */");  
  19.           foreach (var item in dSort)  
  20.           {  
  21.             Console.WriteLine("Keys : " + item.Key + " And   Values : " + item.Value);  
  22.             }  
  23.   
  24.             // Acquire keys and sort  
  25.             var list = dSort.Keys.ToList();  
  26.             list.Sort();  
  27.             Console.WriteLine();  
  28.   
  29.             // For Display the sorted List  
  30.             Console.WriteLine("/* Dictionary After Sorted */");  
  31.             foreach (var item in list)  
  32.             {  
  33.                 Console.WriteLine("{0} : {1}", item,     dSort[item]);  
  34.             }  
  35.             Console.WriteLine();  
  36.             Console.WriteLine("/* Finish */");  
  37.             Console.ReadKey();  
  38.         }  
  39.     }  
  40. }  
Output

key value

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
  1. // Using OrderBy method.  
  2. foreach (var item in dSort.OrderBy(i => i.Value))  
  3. {  
  4.       Console.WriteLine(item);  
  5. }  
Output

array value

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. 


Recommended Free Ebook
Similar Articles