I want to use System.Linq for writing a method that returns the first, most frequent character in a string. eg: "AABABBC" => 'A'. If two letters occur the same, the first one that appears in the string should be returned.
The sample below should work. However, I'm trying to find a more efficient solution, which doesn't imply sorting the characters first. I was thinking of using Enumerable.Aggregate() for counting the repetitions while also iterating through the word. Not sure how to to that, though... Any ideas? Thanks :)
public static char MostAparitionsChar(string word)
{
return word.GroupBy(x => x)
.OrderByDescending(x => x.Count())
.Select(g => g.Key)
.First();
}