2014-05-01 35 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

大,正是我一直在尋找...感謝百萬 –

相關問題