cAMPy
cAMPy

Reputation: 587

List of most occurrences of element

I have a list let's say {1,1,2,2,3,3,3,4,4,4}. I want to find a List of the elements that occur the most often (it has to be a list as there can be a situation like here that 3 and 4 occur most and I need to get that information. How can I achieve this using LINQ?

Upvotes: 1

Views: 376

Answers (4)

Amy B
Amy B

Reputation: 110151

var highCountItems = source
  .GroupBy(item => item)
  .GroupBy(g => g.Count(), g => g.Key)
  .OrderByDescending(counts => counts.Key)
  .First();

int theCount = highCountItems.Key;
var theItems = highCountItems.ToList();

Upvotes: 3

Salah Akbari
Salah Akbari

Reputation: 39966

By Grouping:

var grp = list.GroupBy(i => i).ToList();
int max = grp.Max(c => c.Count());
var most = grp.Where(d => d.Count() == max)
              .Select(c => c.Key).ToList();

Upvotes: 2

Rogger Tân
Rogger Tân

Reputation: 67

A little complicated

var lst_input = new List<int>(new int[] { 1, 1, 2, 2, 3, 3, 3, 4, 4, 4 });
        var result = lst_input.Where(x => lst_input.Max(y => lst_input.Count(z => z == y)) == lst_input.Count(z => z == x)).Distinct().ToList();

But the above code is not effective when dealing with a really big array, since finding max is re-run for each element, and we could distinct the list in the first place. Another more efficient way:

var lst_input = new List<int>(new int[] { 1, 1, 2, 2, 3, 3, 3, 4, 4, 4 });
var tmp = lst_input.Distinct();
var max_val = tmp.Max(y => lst_input.Count(z => z == y));
var result = tmp.Where(x => max_val == lst_input.Count(z => z == x)).ToList();

Upvotes: -1

Gururaj
Gururaj

Reputation: 539

First you will have to group the numbers followed by ordering them so you will get the most frequently occurring number on the top.

int[] numbers = { 1, 1, 2, 2, 3, 3, 3, 4, 4, 4 };
var groups = numbers.GroupBy(i => i).OrderByDescending(g => g.Count());

foreach (var group in groups)
{
      // group.Key -> Represents the number in the list
}

The groups variable will contain all the groups formed from the numbers list ordered by their occurrence, meaning the first group will be the top most occurring group followed by the next. In case of same occurrences, the groups will be ordered by their occurrence in the list for example 3 & 4 have equal occurrences whereas 3 comes first before 4 and hence the group formation will be in same order.

Upvotes: 0

Related Questions