This program will demonstrate to you how to sort descending a dictionary by values in 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 30 31 32 33 34 |
class Program { static void Main(string[] args) { // New Dictionary Dictionary<string, string> Animals = new Dictionary<string, string>(); Animals.Add("a3", "Zebra"); Animals.Add("a4", "Cat"); Animals.Add("a1", "Mouse"); Animals.Add("a2", "Dog"); Animals.Add("a5", "Dolphin"); //Before Sorting Console.WriteLine("Before Sorting by Value"); Console.WriteLine("<::::::::::::::>"); foreach (var animal in Animals) { Console.WriteLine("Key: {0}, Value: {1}", animal.Key, animal.Value); } Console.WriteLine("\nAfter Sorting by Value"); Console.WriteLine("<::::::::::::::>"); //After Sorting foreach (var animal in Animals.OrderByDescending(key => key.Value)) { //animal is a KeyValuePair Object,so you can use "KeyValuePair<string,string>" instead of "var" Console.WriteLine("Key: {0}, Value: {1}", animal.Key, animal.Value); } Console.ReadLine(); } } |
Output: