Filter out distinct elements with condition

2019-02-20 02:13发布

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?

标签: c# linq lambda
3条回答
可以哭但决不认输i
2楼-- · 2019-02-20 03:00

You can use GroupBy to do this:

var results = items.GroupBy(item => item.Code)
                   .Select(g => g.OrderByDescending(i => i.Grade)
                   .First());
查看更多
The star\"
3楼-- · 2019-02-20 03:06

Something like

list.GroupBy(item=>item.Code).Select(item=>new {code = item.Key, grade = item.Max(i=>i.Grade)}).ToList();
查看更多
叼着烟拽天下
4楼-- · 2019-02-20 03:14

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

查看更多
登录 后发表回答