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:

Download  Run Code

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:

Download  Run Code

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.

Download  Run Code

That’s all about getting the key of the highest value of a Dictionary<TKey,TValue> in C#.