Andy
Andy

Reputation: 373

Get the most common (frequent) string entry in array

I have a string array with values in it (duh...).

Is there an easy way of getting the entry which occurs the most? Something like

values[37].getMostOften();

Cheers :)

Upvotes: 6

Views: 1517

Answers (1)

Reed Copsey
Reed Copsey

Reputation: 564333

You can use GroupBy:

var mostCommonValue = values.GroupBy(v => v)
                            .OrderByDescending(g => g.Count())
                            .Select(g => g.Key)
                            .FirstOrDefault();

Upvotes: 16

Related Questions