Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
147 views
in Technique[技术] by (71.8m points)

Is there a "not equal" in a linq join

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;
question from:https://stackoverflow.com/questions/65646637/how-to-check-for-not-equal-condition-below-code-works-for-equal-condition

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...