繁体   English   中英

从字典中查找具有最高值的特定键<int, List<int> &gt; 带有 lambda 表达式

[英]Finding specific key which has highest value from Dictionary<int, List<int>> with lambda expression

我有一本这样的字典——

public static Dictionary<int, List<int>> pegMap = new Dictionary<int, List<int>>();

现在我已经填充了字典,比如 -

Key: 1 => Value: [3,2]
Key: 2 => Value: []
Key: 3 => Value: [6,7]

现在我想找到列表中具有最高值的键。

就像在这种情况下,lambda 应该返回3 ,它表示 key 为3的键值对,因为数字 7 出现在字典中的列表中,而 key 恰好是3

它有点hacky,但应该可以工作。

var dict = new Dictionary<int, List<int>>();

    dict.Add(1, new List<int>() { 1, 2 });
    dict.Add(2, new List<int>() { 4, 5 });
    dict.Add(3, new List<int>() { 1, 7 });

    var max = dict.Select(x => new { Key = x.Key, Value = x.Value.Max() }).OrderByDescending(x => x.Value).First().Key;  
// returns 3
        // Other sample input 
        dict.Add(1, new List<int>() { 1, 2 });
        dict.Add(2, new List<int>() { 4, 7 });
        dict.Add(3, new List<int>() { 1, 2 });
        // returns 2
        dict.Add(1, new List<int>() { 1, 2 });
        dict.Add(2, new List<int>() { 4, 7 });
        dict.Add(3, new List<int>() { 1, 7 });
        // returns 2
        dict.Add(1, new List<int>() { 1,10 });
        dict.Add(2, new List<int>() { 4, 7 });
        dict.Add(3, new List<int>() { 1, 7 });
        // returns 1

编辑:到列表中具有最大值的最小值:

 var min_value_in_maxList = dict.Select(x => new { Key = x.Key, ValueMax = x.Value.Max(), ValueMin = x.Value.Min() }).OrderByDescending(x => x.ValueMax).First().ValueMin;

不幸的是,LINQ to Objects 中没有任何内容使这特别令人愉快。 不过,您可以使用我的MoreLINQ项目中的MaxBy ,但需要在每个列表上使用Max的小技巧:

var maxKey = pegMap.MaxBy(x => x.Value.Max())
                   .Key;

请注意,如果列表中有多个键具有相同的顶部元素,它将返回第一个。

这应该有效,

pegMap.SelectMany(a => a.Value, (a, b) => new {holdKey = a.Key,listValue= b}).OrderByDescending(a=>a.listValue).First().holdKey;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM