Return max repeated item in list

后端 未结 2 740
甜味超标
甜味超标 2020-12-01 14:12
        List prod = new List();
        prod.Add(\"dfg\");
        prod.Add(\"dfg\");
        prod.Add(\"ojj\");
        prod.Add(\"dfg\"         


        
相关标签:
2条回答
  • 2020-12-01 14:49

    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(); 
    
    0 讨论(0)
  • 2020-12-01 15:01

    You can use LINQ:

    string maxRepeated = prod.GroupBy(s => s)
                             .OrderByDescending(s => s.Count())
                             .First().Key;
    
    0 讨论(0)
提交回复
热议问题