Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find the most frequent numbers in an array using LINQ [duplicate]

Tags:

c#

linq

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


1 Answers

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);
}
like image 86
jason Avatar answered Dec 20 '25 15:12

jason



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!