4

I have a Dictionary and I want to find the key which has the highest value.

For example if I had

Key  |  Value
a    |   1
b    |   2
c    |   3

I would want c to be returned.

I have this at the moment but it only searches for the highest value, I'm not sure how to return the key.

var max = occurrences.Max(x => x.Value);
Hossein Narimani Rad
  • 31,361
  • 18
  • 86
  • 116
oneman
  • 811
  • 1
  • 13
  • 31

4 Answers4

9
var maxKey = occurrences.OrderByDescending(x => x.Value).First().Key;
DDan
  • 8,068
  • 5
  • 33
  • 52
5

You need to include MoreLinq and use MaxBy

var result = occurrences.MaxBy(kvp => kvp.Value).Key;
Sajeetharan
  • 216,225
  • 63
  • 350
  • 396
0
        var dict = new Dictionary<string,int>();
        dict.Add("a",1);
        dict.Add("b",2);
        dict.Add("c",3);

        var max= dict.OrderByDescending(x => x.Value).FirstOrDefault();

Remember to check if max is null.

gatsby
  • 1,148
  • 11
  • 12
0

Also here is a solution that consider if there were more than one key with the max 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();
Hossein Narimani Rad
  • 31,361
  • 18
  • 86
  • 116