Andy Lee Xin
Andy Lee Xin

Reputation: 127

LINQ Return max repeated item but sorted in reverse

I have an string array containing names like:

[Alex, Alex, Michael, Michael, Dave, Victor]

That I convert to a List<string>

Then I need to write a function that returns the max repeated item in the list but should be sorted in descending order, which in this case, Michael.

I have followed the LINQ code stated in this link. Which is:

string maxRepeated = prod.GroupBy(s => s)
                     .OrderByDescending(s => s.Count())
                     .First().Key;

However, code returns Alex instead of Michael.

I tried to add another OrderByDescending however it returns Victor.

string maxRepeated = prod.GroupBy(s => s)
                     .OrderByDescending(s => s.Count())
                     .OrderByDescending(b => b)
                     .First().Key;

I am stuck and don't know what needs to be added to achieve the desired result.

Any help is appreciated.

Upvotes: 9

Views: 89

Answers (2)

Tim Schmelter
Tim Schmelter

Reputation: 460208

Not a second OrderByDescending which ignores the previous order but ThenByDescending:

string maxRepeated = prod.GroupBy(s => s)
                     .OrderByDescending(g => g.Count())
                     .ThenByDescending(g => g.Key)
                     .First().Key;

Upvotes: 7

Eric Damtoft
Eric Damtoft

Reputation: 1423

You probably need to add a condition after the "GroupBy" to limit it to groups with more than one item. This is basically the equivalent of "Having" in SQL. I think this would do what you want:

prod.GroupBy(s => s)
    .Where(group => group.Count() > 1)
    .Select(group => group.Key)
    .OrderByDescending(s => s)
    .First();

Upvotes: 1

Related Questions