我有两个对象集合(List list1和List list2).每个被称为"ID"的属性.我知道list2总是会有比list1更多的项目,我只需要一个简单的方法来获取list2中存在的所有项目的集合,但不使用LINQ lambda表达式获取list1.
Luk*_*keH 35
如果您只需要项目的ID,那么Mark的答案将很好地完成.如果您需要自己返回项目(并且它们还没有合适的Equals实现),那么您可以尝试这样的事情:
// assumes that the ID property is an int - change the generic type if it's not
var ids = new HashSet<int>(list1.Select(x => x.ID));
var results = list2.Where(x => !ids.Contains(x.ID));
Run Code Online (Sandbox Code Playgroud)
Mar*_*ers 22
这将获得仅在list2中的ID:
var ids = list2.Select(x => x.Id).Except(list1.Select(x => x.Id));
Run Code Online (Sandbox Code Playgroud)
如果您的对象在具有相同ID时比较相等,那么您可以将其简化为:
var objects = list2.Except(list1);
Run Code Online (Sandbox Code Playgroud)