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

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

问题描述

我试图在 Dictionary< string,double>中获取最大值的键值。结果

这是我到目前为止:

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

聚合是常见的功能概念的LINQ名称折叠

Aggregate is the LINQ name for the commonly known functional concept Fold

它循环遍历集合的每个元素,并应用您提供的任何功能。
这里,我提供的函数是一个返回更大值的比较函数。
循环时, Aggregate 记住上次调用函数时的返回结果。它将它作为变量 l 将其作为我的比较函数。变量 r 是当前选择的元素。

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.

所以在聚合已经遍历整个集合之后,它返回最后一次称之为我的比较功能。然后我从中读取 .Key 成员,因为我知道这是一个字典条目

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天全站免登陆