Return max repeated item in list

2019-01-11 13:00发布

问题:

        List<string> prod = new List<string>();
        prod.Add("dfg");
        prod.Add("dfg");
        prod.Add("ojj");
        prod.Add("dfg");
        prod.Add("e");

In the above code prod List has item "dfg" repeated thrice(max count)... I want "dfg" as the output because this item is repeated maximum times. Can anyone help in this

回答1:

You can use LINQ:

string maxRepeated = prod.GroupBy(s => s)
                         .OrderByDescending(s => s.Count())
                         .First().Key;


回答2:

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();