Domzaza Domzaza - 10 months ago 57
C# Question

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 element in the array. I tried using :

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

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

Answer Source

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);
var mostCommons = groups.Where(x => x.Count == groups.First().Count);

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.