Dictionary sort order
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 35 36 37 38 39 40 41 | class Program { static void Main(string[] args) { //initialize a dictionary with values. Dictionary<int, string> birds = new Dictionary<int, string>() { {1,"Cuban Amazon"}, {2,"Pheasant Cuckoo"}, {3,"African Emerald Cuckoo"}, {4,"Regent Parrot"}, {5,"Guira Cuckoo"} }; Console.WriteLine( "birds dictionary keys and values.........."); foreach (KeyValuePair<int, string> pair in birds) { Console.WriteLine(+ pair.Key + " ........ " + pair.Value); } //descending sorted dictionary by keys. birds = birds.OrderByDescending(x => x.Key).ToDictionary(x => x.Key, x => x.Value); Console.WriteLine("descending sorted dictionary by keys.........."); foreach (KeyValuePair<int, string> pair in birds) { Console.WriteLine(pair.Key + " ........ " + pair.Value); } //ascending sorted dictionary by values. birds = birds.OrderBy(x => x.Value).ToDictionary(x => x.Key, x => x.Value); Console.WriteLine("ascending sorted dictionary by values.........."); foreach (KeyValuePair<int, string> pair in birds) { Console.WriteLine(pair.Key + " ........ " + pair.Value); } Console.ReadLine(); } } |
Output: