1

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?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
cAMPy
  • 567
  • 2
  • 8
  • 25
  • What is a condition for "most often"? More then two times? – kat1330 Jun 04 '17 at 18:12
  • it can be that all the elements appear only once, then I would get a whole list back. So most often is just the element(s) that appear maximum times. – cAMPy Jun 04 '17 at 18:14
  • int[] numbers = { 1, 1, 2, 2, 3, 3, 3, 4, 4, 4 }; var groups = numbers.GroupBy(i => i).OrderByDescending(g => g.Count()); – Gururaj Jun 04 '17 at 18:34
  • https://stackoverflow.com/questions/43403243/c-sharp-how-to-find-the-most-common-and-the-least-common-integers-in-an-array/43403684#43403684 – Slai Jun 04 '17 at 18:46

4 Answers4

3
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();
Amy B
  • 108,202
  • 21
  • 135
  • 185
2

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();
Salah Akbari
  • 39,330
  • 10
  • 79
  • 109
0

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.

Gururaj
  • 539
  • 2
  • 8
-1

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();
Rogger Tân
  • 71
  • 2
  • 6