【问题标题】:How can I get the value with most occurrences in a collection?如何获得集合中出现次数最多的值?
【发布时间】:2014-05-01 13:26:12
【问题描述】:

我有一个int? 列表,它可以有 3 个不同的值:null、1 和 2。 我想知道其中哪一个出现在我的列表中最多。为了按值对它们进行分组,我尝试使用:

MyCollection.ToLookup(r => r)

如何获得出现次数最多的值?

【问题讨论】:

    标签: c# linq linq-to-objects


    【解决方案1】:

    您不需要查找,一个简单的GroupBy 就可以了:

    var mostCommon = MyCollection
      .GroupBy(r => r)
      .Select(grp => new { Value = grp.Key, Count = grp.Count() })
      .OrderByDescending(x => x.Count)
      .First()
    
    Console.WriteLine(
      "Value {0} is most common with {1} occurrences", 
      mostCommon.Value, mostCommon.Count);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-01-25
      • 2016-09-26
      • 1970-01-01
      • 2018-11-06
      • 1970-01-01
      • 1970-01-01
      • 2022-11-28
      • 1970-01-01
      相关资源
      最近更新 更多