문제

I have a list of 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. 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:

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 ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top