This program will demonstrate the example of the sorting a given 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.OrderBy(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(); } } |
When you run the program, the output will be:
above program, we have a Dictionary with countries and their respective animals stored in a variable animals.
We have two “foreach”. The first one shows the state before the sorting, and the second one shows the status after the sorting.