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?
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With