2014-05-01 36 views
1

我有一个列表int?,可以有3个不同的值:空,1和2. 我想知道他们哪些发生在我的列表中最多。对他们来说,通过数值组我试图用:如何获得集合中出现次数最多的值?

MyCollection.ToLookup(r => r) 

我怎样才能得到大多数发生的价值?

回答

5

你并不需要一个查找,一个简单的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); 
+0

大,正是我一直在寻找...感谢百万 –

相关问题