我正在尝试完成下面的LINQ查询,但是我需要一个“不等于”而不是相等,以便filteredEmployees的所有雇员都来自groupA减去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:
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<T>传递为Except的参数。我在MiscUtil中有一个ProjectionEqualityComparer类,可以轻松构建所需的比较器:
// 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);

10-05 20:15