Get key of highest value of a Dictionary in C#
This post will discuss how to get the key of the highest value of a Dictionary<TKey,TValue> in C#.
1. Using Enumerable.Aggregate() Method
LINQ’s Aggregate() method applies an accumulator function to each item of a sequence. It can be used as follows to find the maximum value of a dictionary:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
using System; using System.Linq; using System.Collections.Generic; public class Example { public static void Main() { Dictionary<string, int> dict = new Dictionary<string, int>() { {"A", 1}, {"B", 2}, {"C", 3} }; var maxValueKey = dict.Aggregate((x, y) => x.Value > y.Value ? x : y).Key; Console.WriteLine(maxValueKey); // C } } |
2. Using foreach loop
Alternatively, you can write your own function for getting the key of the maximum value of a dictionary. The idea is to loop through the dictionary mappings using the foreach statement and keep track of the KeyValuePair with maximum value. This is demonstrated below:
|
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 |
using System; using System.Collections.Generic; public static class Extensions { public static K maxValueKey<K>(this IDictionary<K,int> dict) { KeyValuePair<K,int> max = new KeyValuePair<K,int>(); foreach (var entry in dict) { if (entry.Value > max.Value) { max = entry; } } return max.Key; } } public class Example { public static void Main() { Dictionary<string, int> dict = new Dictionary<string, int>() { {"A", 1}, {"B", 2}, {"C", 3} }; var maxValueKey = dict.maxValueKey(); Console.WriteLine(maxValueKey); // C } } |
3. Using Enumerable.OrderByDescending() Method
Finally, you can sort the Dictionary<TKey,TValue> by using OrderByDescending() according to its value. The key of the first element is the key with the maximum value. Similarly, to find the key with the lowest value, use OrderBy() method.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
using System; using System.Linq; using System.Collections.Generic; public class Example { public static void Main() { Dictionary<string, int> dict = new Dictionary<string, int>() { {"A", 1}, {"B", 2}, {"C", 3} }; var maxValueKey = dict.OrderByDescending(x => x.Value).First().Key; Console.WriteLine(maxValueKey); // C } } |
That’s all about getting the key of the highest value of a Dictionary<TKey,TValue> in C#.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)