我有一个 int? 列表,它可以有 3 个不同的值:null、1 和 2。 我想知道它们中哪一个在我的列表中出现最多。为了按值(value)对它们进行分组,我尝试使用:
MyCollection.ToLookup(r => r)
如何获取出现次数最多的值?
请您参考如下方法:
您不需要查找,一个简单的 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);
