Click here to Skip to main content
15,886,518 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
suppose I have a
C#
Dictionary<string,double> results

I need to get the key of the highest value of a Dictionary in C#, from

(http://stackoverflow.com/questions/2805703/good-way-to-get-the-key-of-the-highest-value-of-a-dictionary-in-c-sharp[^]

I have:

C#
var max = results.Aggregate((l, r) => l.Value > r.Value ? l : r).Key;


How should I change the syntax to manage also the case in which the dictionary can contain null value. (if null, I do not want to consider that associated key, just skip that key)

Thanks
Posted

1 solution

What about this:

C#
Dictionary<string,double?> results = new Dictionary<string,double?>(){
    {"A", 12.0},
    {"B", 10.0},
    {"C", null},
    {"D", 15.0},
    {"E", 5.0}
};

var max = from x in results where x.Value == results.Max(v => v.Value) select x.Key;

max.Dump();
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900