2

I'm trying to find a clever way using linq to examine an IEnumerable and find the max occurrences of some element.

"aba".SomeLinqExpression(); // => 'a'

or

(new List<int>{1, 2, 3, 4, 1, 2, 1}).SomLinqExpression(); // => 1

Is there an easy built in way to do this I think I need an aggregation query but Aggregate and Count don't seem to do it. Maybe groupby?

EDIT: Clarification

I'm looking to get access to the most often seen value. I don't care how ties are handled.

if we have a string

"abcda" // note that there are 2 'a' characters.

Since 'a' is the most common thing in the sequence I want this operation to return 'a'

"abcda".SomeLinqExpression(); // returns 'a'
t3dodson
  • 3,734
  • 2
  • 31
  • 38

1 Answers1

3

Well, I guess this will work:

"aqejqkndaasaamd".GroupBy(x => x).OrderByDescending(g => g.Count()).First().Key
Athari
  • 32,606
  • 14
  • 101
  • 138