How do I find the key that has the highest value in a C # dictionary?
I have a dictionary and I want to find the key with the highest value.
For example, if I had
Key | Value
a | 1
b | 2
c | 3
I want c to be returned.
I have this at the moment, but it only looks for the highest value, I'm not sure how to return the key.
var max = occurrences.Max(x => x.Value);
+3
source to share
4 answers
Also is there a solution that takes into account if there was more than one key with the maximum value in the dictionary?
Dictionary<char, int> dic = new Dictionary<char, int>();
dic.Add('a', 1);
dic.Add('b', 2);
dic.Add('c', 3);
dic.Add('d', 3);
var maxValue = (int)dic.Max(i => i.Value);
List<char> maxKeys = dic.Where(i => i.Value == maxValue).Select(i => i.Key).ToList();
0
source to share