Filter out distinct elements with condition

2019-02-20 02:32发布

问题:

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:

  1. Code: 1, Grade: 10
  2. Code: 1, Grade: 20
  3. Code: 2, Grade: 1

Expected List:

  1. Code: 1, Grade: 20
  2. Code: 2, Grade: 1

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?

回答1:

You can use GroupBy to do this:

var results = items.GroupBy(item => item.Code)
                   .Select(g => g.OrderByDescending(i => i.Grade)
                   .First());


回答2:

I suggest that you first GroupBy the Code property, and then select the Max of each element in the group



回答3:

Something like

list.GroupBy(item=>item.Code).Select(item=>new {code = item.Key, grade = item.Max(i=>i.Grade)}).ToList();


标签: c# linq lambda