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,949
  • 2
  • 29
  • 40
  • `Where` and `Count`? `GroupBy`, `OrderByDescending` and `First`? this question is not clear to me - please elaborate! –  May 22 '15 at 21:08
  • 1
    GroupBy, then OrderByDescending, then select the first Key. – Sriram Sakthivel May 22 '15 at 21:09
  • @SriramSakthivel sorry for the duplicate I searched for something like that but didn't see it. – t3dodson May 22 '15 at 21:12
  • 1
    No worries. If you have used right keyword, you'd have got it. FYI this is my search term "c# find max occurrence of character in string" and first result is the duplicate link :) – Sriram Sakthivel May 22 '15 at 21:14

1 Answers1

3

Well, I guess this will work:

"aqejqkndaasaamd".GroupBy(x => x).OrderByDescending(g => g.Count()).First().Key
Athari
  • 33,702
  • 16
  • 105
  • 146