【发布时间】:2014-05-01 13:26:12
【问题描述】:
我有一个int? 列表,它可以有 3 个不同的值:null、1 和 2。
我想知道其中哪一个出现在我的列表中最多。为了按值对它们进行分组,我尝试使用:
MyCollection.ToLookup(r => r)
如何获得出现次数最多的值?
【问题讨论】:
标签: c# linq linq-to-objects
我有一个int? 列表,它可以有 3 个不同的值:null、1 和 2。
我想知道其中哪一个出现在我的列表中最多。为了按值对它们进行分组,我尝试使用:
MyCollection.ToLookup(r => r)
如何获得出现次数最多的值?
【问题讨论】:
标签: c# linq linq-to-objects
您不需要查找,一个简单的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);
【讨论】: