Is there a “not equal” in a linq join

时光怂恿深爱的人放手 提交于 2019-11-27 12:04:37

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<string>(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<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);

No, a "not equal" operator would get you all combinations of groupA and groupB except the ones where the items were the same.

Using the Except method gets you what you want:

var filteredEmployees = groupA.Except(groupB);

In Entity Framework 6, I've gotten better results using

var filteredEmployees = groupA.Where(a => !groupB.Select(b => b.Name).Contains(a.Name));

use of this code for decreased server cost :

The code works very fast compared to other code

        var noExistList = (from n in groupA 
                                join o in groupA  on n.Id equals o.Id into p
                                where p.Count() == 0
                                select n).ToList();

note: groupA is a new list for add.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!