Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ Return max repeated item but sorted in reverse

Tags:

c#

linq

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.

like image 633
Andy Lee Xin Avatar asked Sep 27 '18 12:09

Andy Lee Xin


1 Answers

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;
like image 158
Tim Schmelter Avatar answered Nov 10 '22 00:11

Tim Schmelter