Find the most frequent numbers in an array using LINQ

c#, linq

Solution

The key here is using `Enumerable.GroupBy` and the aggregation method `Enumerable.Count`:

List<int> list = new List<int>() { 1,1,2,2,3,4,5 };

// group by value and count frequency
var query = from i in list
            group i by i into g
            select new {g.Key, Count = g.Count()};

// compute the maximum frequency
int whatsTheFrequencyKenneth = query.Max(g => g.Count);

// find the values with that frequency
IEnumerable<int> modes = query
                              .Where(g => g.Count == whatsTheFrequencyKenneth)
                              .Select(g => g.Key);

// dump to console
foreach(var mode in modes) {
    Console.WriteLine(mode);
}

Problem

``` List<int> a = new List<int>{ 1,1,2,2,3,4,5 }; ``` What's the quickest way to do this with LINQ? I'm new to LINQ

Original source

Related problems