是否存在“不等于"?在 linq 连接中 [英] Is there a "not equal" in a linq join
问题描述
我正在尝试完成下面的 LINQ 查询,但我需要一个不等于"而不是等于,以便过滤员工拥有 groupA 减去 groupB 的所有员工.
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.
List<Employee> groupA = getEmployeeA();
List<Employee> groupB = getEmployeeB();
var filteredEmployees = from a in groupA
join b in groupB on a.Name equals b.Name
select a;
推荐答案
你不需要加入:
var filteredEmployees = groupA.Except(groupB);
请注意,这将是一系列唯一员工 - 因此,如果 groupA
中有任何重复项,则它们只会在 filteredEmployees
中出现一次.当然,它还假设您有一个合理的相等比较器1.如果您需要专门针对名称,可以使用 ExceptBy
来自 MoreLINQ:
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);
或者不进入第三方库:
var groupBNames = new HashSet<string>(groupB.Select(x => x.Name));
var filteredEmployees = groupA.Where(x => !groupBNames.Contains(x.Name));
<小时>
1 正如评论中所指出的,您可以将 IEqualityComparer
作为参数传递给 Except
.我在 MiscUtil 中有一个 ProjectionEqualityComparer
类,这使得构建一个您需要的那种比较器:
1 As pointed out in the comments, you can pass in an IEqualityComparer<T>
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<Employee>.Create(x => x.Name);
var filteredEmployees = groupA.Except(groupB, comparer);
这篇关于是否存在“不等于"?在 linq 连接中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!