I’m trying to get the key of the maximum value in the Dictionary<string, double> results.
This is what I have so far:
double max = results.Max(kvp => kvp.Value);
return results.Where(kvp => kvp.Value == max).Select(kvp => kvp.Key).First();
However, since this seems a little inefficient, I was wondering whether there was a better way to do this.
edit: .NET 6 introduced a new method
var max = results.MaxBy(kvp => kvp.Value).Key;You should probably use that if you can.
I think this is the most readable O(n) answer using standard LINQ.
edit: explanation for CoffeeAddict
Aggregateis the LINQ name for the commonly known functional concept FoldIt loops over each element of the set and applies whatever function you provide.
Here, the function I provide is a comparison function that returns the bigger value.
While looping,
Aggregateremembers the return result from the last time it called my function. It feeds this into my comparison function as variablel. The variableris the currently selected element.So after aggregate has looped over the entire set, it returns the result from the very last time it called my comparison function. Then I read the
.Keymember from it because I know it’s a dictionary entryHere is a different way to look at it [I don’t guarantee that this compiles 😉 ]