How to Sort a Dictionary Object by Values in C#

Microsoft .NET provides us with classes such as SortedDictionary that allows the elements of a Dictionary class to be sorted by Keys. However, in some scenarios we want the Dictionary elements to be sorted by the values present in each element. Today, in this post we will see how can we sort a Dictionary Object by Values in C#.

Let us straightaway go to the function:

  1. public void SortDictionary()    
  2. {    
  3.     Dictionary<stringstring> diction = new Dictionary<string,string>();    
  4.     diction.Add("3""three");    
  5.     diction.Add("1""one");    
  6.     diction.Add("5""five");    
  7.     diction.Add("2""two");    
  8.     
  9.     List<keyvaluepair<stringstring="">> sortList = diction.ToList();    
  10.     
  11.     var sorted = from entry in diction orderby entry.Value ascending select entry;         
  12. }  
In the above code snippet, we are declaring a Dictionary object and then converting it into an object of List type so that we can use LINQ on top of this. Once the dictionary object is converted into a List, we use LINQ to sort the items using its value and assign it to the variable sorted. Now, the sorted variable contains the sorted dictionary based on its values.

Hope you liked this. Keep learning and sharing.

 

Ebook Download
View all
Learn
View all
Think. Innovate. Grow.