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

Mee*_*mfp 1 c# linq linq-to-objects

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

MyCollection.ToLookup(r => r)
Run Code Online (Sandbox Code Playgroud)

如何获得最多出现的值?

Avi*_*ish 5

你不需要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);
Run Code Online (Sandbox Code Playgroud)