Click here to Skip to main content
15,887,596 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I need to select items with the highest rank per attribute
I have a functional ranking in linq that looks like this:
C#
MyCollection.GroupBy(c => c.Attribute).Select(g => g.OrderByDescending(c => c.Prio).First())
And it works fine except when I get ties in the ranking I only get one of the tied items.

Does anyone know how to get all of the tied items with the highest priority?

What I have tried:

C#
MyCollection.GroupBy(c => c.Attribute).Select(g => g.OrderByDescending(c => c.Prio).First())
Posted
Updated 13-May-18 23:51pm

1 solution

You can't do it automatically, because you have very specifically told it to only return one element from each group - that's what First does!
Try this:
MyCollection.GroupBy(c => c.Attribute).SelectMany(g => g.Where(p => p.Prio == g.Max(h => h.Prio)))
 
Share this answer
 
Comments
Jörgen Andersson 14-May-18 6:32am    
Oh, I knew it was wrong alright, I just couldn't wrap my head around to get it right.
I have meanwhile solved it though, using a nested Groupby. But your solution is better and as simple as I thought it should be.
OriginalGriff 14-May-18 6:35am    
:laugh:
Ain't it always the way? When you ask the question, it solves itself...

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900