如何获取集合中出现次数最多的值

本文关键字:何获取 获取 集合 | 更新日期: 2023-09-27 18:01:13

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

MyCollection.ToLookup(r => r)

如何获得发生次数最多的值?

如何获取集合中出现次数最多的值

您不需要Lookup,一个简单的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);