是否存在“不相等"的问题?在linq中加入 [英] Is there a "not equal" in a linq join

查看:100
本文介绍了是否存在“不相等"的问题?在linq中加入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试完成下面的LINQ查询,但我需要一个不等于"而不是相等,以便filterEmployees拥有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);

或者无需进入第三方库:

Or without going into a third party library:

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类,可轻松构建您自己的比较器需要:


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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆