【问题标题】:How to get Max value from list, but if there are 2 or more same value record then get all如何从列表中获取最大值,但如果有 2 个或更多相同的值记录,则获取全部
【发布时间】:2016-06-08 14:12:41
【问题描述】:

我有一个 ex 的键和值列表:-

Key Value
21   2
23   1
24   2

我想要最大值记录,我可以使用 max(x=>x.value) 在 linq 中获得,但在我的情况下,21 和 24 都有最大值,在这种情况下意味着当有 2 个或更多时键具有相同的最大值然后我想要所有这些我怎样才能获得预期的结果。

请给我提示或想法。

问候, 维尼特帕特尔

【问题讨论】:

  • 我已经读了几遍了,我还是不明白你在做什么。
  • 你的意思是 Key,Value 的总和应该是最大值吗?

标签: c# linq


【解决方案1】:

如果你有这样的列表:

List<KeyValuePair<int, int>> keyValues = ...

可以按值分组,然后用max键选择分组:

var keys = keyValues.GroupBy(kv => kv.Value)
                    .OrderByDescending(g => g.Key)
                    .FirstOrDefault()
                    .Select(kv => kv.Key);

【讨论】:

    【解决方案2】:

    你可以这样做。

     var keyvalue = list.GroupBy(x => x.Value)             // Group on value
                        .OrderByDescending(x => x.Key)     // Order the group and 
                        .First()                           // Take first item in a group 
                        .OrderByDescending(x=>x.Key)       // Sort and get max Key,value combination.  
                        .FirstOrDefault();
    

    查看Demo

    【讨论】:

    • Select(x=&gt;x) 不做任何事情,总是可以删除。
    • 是的,已删除。谢谢@juharr
    • @juharr:实际上这不是相当正确的。考虑一下:var a = new List&lt;int&gt;() { whatever } ; var b = a.Select(x=&gt;x); 显然ab 具有非常不同的语义;一方面,您可以在a 上致电Add,但不能在b 上致电。 The rule actually is that you can safely remove Select(x=&gt;x) only when the receiver of the select is already a query.这就是为什么 C# 编译器将为from x in a select x 生成a.Select(x=&gt;x),但会在from x in a where whatever select x 中省略Select(x=&gt;x);由于已知结果是查询,因此可以安全地删除选择。
    【解决方案3】:

    这是另一种方法:

    var entries = new Dictionary<int, int>()
    {
        {21, 2},
        {23, 1},
        {24, 2}
    };
    
    // First we select the max value.
    int maxValue = entries.Max(kvp => kvp.Value);
    
    // Or you can select the max value in this simpler way.
    maxValue = entries.Values.Max();
    
    // Then we select entries that have the max value.
    var maxEntries =
        entries
            .Where(kvp => kvp.Value == maxValue)
            .ToDictionary(kvp => kvp.Key, kvp => kvp.Value);
    

    【讨论】:

      猜你喜欢
      • 2020-10-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-06-26
      • 2020-11-03
      • 1970-01-01
      • 2019-06-30
      相关资源
      最近更新 更多