Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Find most common strings in string array

I have this one problem. There is a string

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

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

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

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

like image 612
Domzaza Avatar asked Nov 29 '22 23:11

Domzaza


1 Answers

First will obviously only select the very first element of your sequence. However you need all groups with an equal number. So select the name and number per group and order afterwards. Finally select all those groups having the same count as the very first group.

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: You could also use TakeWhile instead of Where in the last statement which will avoid unnecessary comparisons for the last elements in the groups-list and stops immediately when the first group was found having less elements than the first one:

var mostCommons = groups.TakeWhile(x => x.Count == groups.First().Count);
like image 97
MakePeaceGreatAgain Avatar answered Dec 12 '22 07:12

MakePeaceGreatAgain