Dictionary sort by value descending
C# Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | class Program { static void Main(string[] args) { //initialize a dictionary with values. Dictionary<int, string> plants = new Dictionary<int, string>() { {1,"Bur Oak"}, {2,"Algerian Oak"}, {3,"Coast Live Oak"}, {4,"Northern Red Oak"}, {5,"Swamp Oak"} }; Console.WriteLine("plants dictionary keys and values.........."); foreach (KeyValuePair<int, string> pair in plants) { Console.WriteLine(pair.Key + " ........ " + pair.Value); } Console.WriteLine("\n\ndictionary keys and values descending sorted by values.........."); foreach (KeyValuePair<int, string> pair in plants.OrderByDescending(pair => pair.Value)) { Console.WriteLine(pair.Key + " ........ " + pair.Value); } Console.ReadLine(); } } |
Output:

How to sort a Dictionary by value in descending order in C#