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


var maxKey = occurrences.OrderByDescending(x => x.Value).First().Key;

      



+8


source


You need to enable and use MoreLinq

MaxBy



var result = occurrences.MaxBy(kvp => kvp.Value).Key;

      

+5


source


        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.

0


source


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







All Articles