Question

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?

Was it helpful?

Solution

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);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top