How can I use Linq to get distinct results filtered by property

This question already has an answer here:

  • LINQ's Distinct() on a particular property 17 answers

  • List<Tool> distinctTool = tools
      .GroupBy(p => p.Number)
      .Select(g => g.OrderByDescending(q => q.Source == "M1").First())
      .ToList();
    

    您需要按照编号对Tools进行分组,并获取其中的First()

    List<Tool> distinctTool = tools
      .GroupBy(p => p.Number)
      .Select(g => g.OrderByDescending(q => q.Source == "M1").First())      
      .ToList();
    

    尝试按数字分组并获取第一个元素,

    List<Tool> distinctTool = tools.GroupBy(p => p.Number)
                                   .Select(f => f.OrderByDescending(q => q.Source == "M1").First())
                                   .ToList();
    

    WORKING FIDDLE

    链接地址: http://www.djcxy.com/p/51306.html

    上一篇: 仅在内部列出不同的值

    下一篇: 我如何使用Linq获取按属性过滤的独特结果