Return max repeated item in list

Not the absolutely most efficient, but it works:

var maxRepeatedItem = prod.GroupBy(x => x)
                          .OrderByDescending(x => x.Count())
                          .First().Key;

This is more efficient:

var maxRepeatedItem = prod.GroupBy(x => x)
                          .MaxBy(x => x.Count())
                          .First().Key;

but it requires MoreLinq‘s extension MaxBy

EDIT (as per comment) :

If you want all the max repeated elements in case of ties, here’s a possible solution:

var grouped = prod.ToLookup(x => x);
var maxRepetitions = grouped.Max(x => x.Count());
var maxRepeatedItems = grouped.Where(x => x.Count() == maxRepetitions)
                              .Select(x => x.Key).ToList(); 

Leave a Comment