Filter out distinct elements with condition

前端 未结 3 1468
情深已故
情深已故 2021-01-16 14:51

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.

相关标签:
3条回答
  • 2021-01-16 15:18

    You can use GroupBy to do this:

    var results = items.GroupBy(item => item.Code)
                       .Select(g => g.OrderByDescending(i => i.Grade)
                       .First());
    
    0 讨论(0)
  • 2021-01-16 15:21

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

    0 讨论(0)
  • 2021-01-16 15:21

    Something like

    list.GroupBy(item=>item.Code).Select(item=>new {code = item.Key, grade = item.Max(i=>i.Grade)}).ToList();
    
    0 讨论(0)
提交回复
热议问题