【问题标题】:Finding specific key which has highest value from Dictionary<int, List<int>> with lambda expression使用 lambda 表达式从 Dictionary<int, List<int>> 中查找具有最高值的特定键
【发布时间】:2012-03-24 16:47:29
【问题描述】:

我有一本这样的字典 -

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 出现在字典中的列表中,其中键恰好是 3

【问题讨论】:

    标签: c# .net dictionary lambda .net-3.5


    【解决方案1】:

    它有点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;
    

    【讨论】:

    • 你能解释一下lambda中的新关键字吗?我没有得到那部分。
    • 在这种情况下,new 生成一个具有两个属性 Key 和 Value 的匿名类型。请参阅此问题以获取详细答案。 stackoverflow.com/questions/48668/…
    • 再问一个问题,如果我想在存在 max 的 List&lt;int?&gt; 中找到最小的数字怎么办。
    • 查看我的编辑。只需添加另一个匿名变量并在最后查询那个变量。
    【解决方案2】:

    这应该可以,

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

    【讨论】:

    • :( ,抱歉几乎和@Alex的回答一样。回答之前没有刷新
    • 没问题。我认为这是Stack Overflow 应该考虑的事情。包括我在内的很多人在回答或评论之前不会刷新。一个实时问题。
    【解决方案3】:

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

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-02-22
      • 1970-01-01
      • 1970-01-01
      • 2014-01-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-11-08
      相关资源
      最近更新 更多