Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return max repeated item in list

Tags:

        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

like image 477
Jois_Cool Avatar asked Mar 03 '13 10:03

Jois_Cool


People also ask

How do you find the maximum occurrence of an element in a list?

Given a list, the task is to find the number of occurrences of the largest element of the list. Method 1: The naive approach is to find the largest element present in the list using max(list) function, then iterating through the list using a for loop and find the frequency of the largest element in the list.

How do you get the most repeated item in a list Python?

Make use of Python Counter which returns count of each element in the list. Thus, we simply find the most common element by using most_common() method.

How do you find the maximum occurrence of a character in a list Python?

Method 1 : Naive method + max() In this method, we simply iterate through the string and form a key in a dictionary of newly occurred element or if element is already occurred, we increase its value by 1. We find maximum occurring character by using max() on values.


2 Answers

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(); 
like image 121
digEmAll Avatar answered Sep 22 '22 06:09

digEmAll


You can use LINQ:

string maxRepeated = prod.GroupBy(s => s)
                         .OrderByDescending(s => s.Count())
                         .First().Key;
like image 42
Matten Avatar answered Sep 19 '22 06:09

Matten