[英]How can I get the value with most occurrences in a collection?
I have a list of int?
我有一个
int?
列表int?
that can have 3 different values: null, 1, and 2. I would like to know which of them occurs the most in my list. 可以有3个不同的值:null,1和2。我想知道其中哪个出现在我的列表中最多。 To group them by value I tried to use:
要按值对它们进行分组,我尝试使用:
MyCollection.ToLookup(r => r)
How can I get the value with most occurrence? 如何获得最多的价值?
You don't need a Lookup, a simple GroupBy would do: 您不需要查找,一个简单的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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.