Is there a “not equal” in a linq join

后端 未结 4 2277
孤街浪徒
孤街浪徒 2020-12-05 04:27

I am trying accomplish the LINQ query below but I need a \"not equal\" instead of equal, so that filteredEmployees has all employees from groupA minus groupB.



        
4条回答
  •  时光说笑
    2020-12-05 05:09

    You don't need a join for that:

    var filteredEmployees = groupA.Except(groupB);
    

    Note that this will be a sequence of unique employees - so if there are any duplicates in groupA, they will only appear once in filteredEmployees. Of course, it also assumes you've got a reasonable equality comparer1. If you need to go specifically on name, you can use ExceptBy from MoreLINQ:

    var filteredEmployees = groupA.ExceptBy(groupB, employee => employee.Name);
    

    Or without going into a third party library:

    var groupBNames = new HashSet(groupB.Select(x => x.Name));
    var filteredEmployees = groupA.Where(x => !groupBNames.Contains(x.Name));
    

    1 As pointed out in the comments, you can pass in an IEqualityComparer as an argument to Except. I have a ProjectionEqualityComparer class in MiscUtil which makes it easy to build a comparer of the kind you need:

    // I can't remember the exact method name, but it's like this :)
    var comparer = ProjectionEqualityComparer.Create(x => x.Name);
    var filteredEmployees = groupA.Except(groupB, comparer);
    

提交回复
热议问题