04/06/2015 by Nitesh

How To Sort A Dictionary Object by Values in C#


Microsoft .Net provides us with classes like 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 straight away go to the function –

   public void SortDictionary()
     Dictionary<string, string> diction = new Dictionary<string,string>();
     diction.Add("3", "three");
     diction.Add("1", "one");
     diction.Add("5", "five");
     diction.Add("2", "two");

     List<keyvaluepair<string, string="">> sortList = diction.ToList();

     var sorted = from entry in diction orderby entry.Value ascending select entry;     

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 like this. Keep learning and sharing.