Dictionary sort by value
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,"Orange Milkweed"}, {2,"Horsetail Milkweed"}, {3,"American Nightshade"}, {4,"Yellow Milkweed"}, {5,"Swamp Milkweed"} }; Console.WriteLine( "plants dictionary keys and values.........."); foreach (KeyValuePair<int, string> pair in plants) { Console.WriteLine(pair.Key + " ........ " + pair.Value); } Console.WriteLine("\nplants dictionary keys and values sorted by values.........."); foreach (KeyValuePair<int, string> pair in plants.OrderBy(pair => pair.Value)) { Console.WriteLine(pair.Key + " ........ " + pair.Value); } Console.ReadLine(); } } |
Output: