从Dictionary <int,list <int =“”>&gt;中查找具有最高值的特定键。与lambda表达式</int,>

时间:2012-03-07 06:17:26

标签: .net .net-3.5 dictionary lambda

我有一个像这样的字典 -

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,它表示键值为3的键值对,因为数字7出现在字典中的键中,其中键恰好是{ {1}}。

3 个答案:

答案 0 :(得分: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;

答案 1 :(得分:1)

不幸的是LINQ to Objects没有内置任何东西,这使得这个特别令人愉快。您可以使用MaxBy项目中的MoreLINQ,但需要在每个列表中使用Max

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

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

答案 2 :(得分:1)

这应该有用,

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