C # Find the most common lines in an array of strings

I have this problem. There is a line

string [5] names = { "John", "Sam", "Harry", "Sam", "John" }

I need to find the most common elements in an array. I tried using:

string MostCommon = names.GroupBy(v => v)
    .OrderByDescending(g => g.Count())
    .First()
    .Key;

Unfortunately, it finds only one element, i.e. MostCommon = John, and in this case I need not only John, but also Sam. How could I do this? Maybe LINQ is not needed in this case?

+4
source share
3 answers

This can be done as follows:

 var nameGroup = names.GroupBy(x => x);
 var maxCount = nameGroup.Max(g => g.Count());
 var mostCommons = nameGroup.Where(x => x.Count() == maxCount).Select(x => x.Key).ToArray();
+5
source

First, , . . , . , , , .

var groups = names.GroupBy(x => x)
    .Select(x => new { x.Key, Count = x.Count() })
    .OrderByDescending(x => x.Count);
int max = groups.First().Count;
var mostCommons = groups.Where(x => x.Count == max);

EDIT: TakeWhile Where , groups -list , , :

var mostCommons = groups.TakeWhile(x => x.Count == groups.First().Count);
+9

LINQ linq , .

string MostCommon = names.GroupBy(v => v)
    .OrderByDescending(g => g.Count())
    .First();

int count = names.Where(x => x == MostCommon).Count();

var mostCommonList = names.GroupBy(v => v)
    .Where(g => g.Count() == count);
+4

Source: https://habr.com/ru/post/1655215/


All Articles