Reputation: 57469
I have a list of objects that has some duplicates by a property. I would like to get all non-duplicate and also 1 of the duplicates based on a condition.
For eg.
Lists:
Expected List:
The condition would be that of the duplicate elements, grab the one with the highest Grade
. How would I write the lambda or linq expression to do this?
Upvotes: 1
Views: 961
Reputation: 564433
You can use GroupBy
to do this:
var results = items.GroupBy(item => item.Code)
.Select(g => g.OrderByDescending(i => i.Grade)
.First());
Upvotes: 5
Reputation: 3348
Something like
list.GroupBy(item=>item.Code).Select(item=>new {code = item.Key, grade = item.Max(i=>i.Grade)}).ToList();
Upvotes: 0
Reputation: 6742
I suggest that you first GroupBy
the Code
property, and then select the Max
of each element in the group
Upvotes: 0