在C#中获取Dictionary最高值的键,其中value可以为null [英] get the key of the highest value of a Dictionary in C# where value may be null

查看:2048
本文介绍了在C#中获取Dictionary最高值的键,其中value可以为null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个

 Dictionary< string,double>结果



我需要在C#中获取字典最高值的关键字,来自



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



我有:



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





如何更改语法以管理字典可以包含空值的情况。(如果为null,我不想考虑该关联键,只需跳过该键)



谢谢

解决方案

这个怎么样:



字典<字符串, double >  results =  new 字典<字符串, double > () {
{ A 12 . 0 },
{ B 10 0 },
{ C null },
{ D 15 0 },
{ E 5 0 }
};

var max = 来自 x in 结果其中​​ x.Value == results.Max(v = > v.Value)选择 x.Key;

max.Dump();


suppose I have a

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:

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

解决方案

What about this:

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();


这篇关于在C#中获取Dictionary最高值的键,其中value可以为null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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