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:
- 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;
- }
Hope you liked this. Keep learning and sharing.

Danny SchneiderPosted Jun 4, 2015, 5:19 PM
Hi Nitesh Luharuka, why you convert the dictionary to a list first? Is there any advantage? In my opinion a better way is to use the integrated dictionary's orderby function: diction.OrderBy(x => x.Value)?