好方法字典的最高值在C#中的关键 [英] Good way to get the key of the highest value of a Dictionary in C#

查看:464
本文介绍了好方法字典的最高值在C#中的关键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图让在词典&LT最大值的关键;字符串,双>结果

这是我迄今为止:

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.

推荐答案

我觉得这个使用标准LINQ是最可读的O(n)的答案。

I think this is the most readable O(n) answer using standard LINQ.

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

编辑:解释CoffeeAddict

edit: explanation for CoffeeAddict

总结是俗称功能概念的折叠

它遍历集合的每个元素,并应用您提供力所能及的作用。
在这里,我提供的功能是返回更大值的比较功能。
虽然循环,总结会记住它最后一次打电话给我的函数的返回结果。它送入我的比较功能变量这一点。变量研究是当前所选元素。

It 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, Aggregate remembers the return result from the last time it called my function. It feeds this into my comparison function as variable l. The variable r is 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 .Key member from it because I know it's a dictionary entry

下面是用不同的方式来看待它[我不保证本编译)]

Here is a different way to look at it [I don't guarantee that this compiles ;) ]

var l = results[0];
for(int i=1; i<results.Count(); ++i)
{
    var r = results[i];
    if(r.Value > l.Value)
        l = r;        
}
var max = l.Key;

这篇关于好方法字典的最高值在C#中的关键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆