使用Linq从列表中删除与属性相交的项目
我有2个共享相同属性的不同对象(foo
和bar
)的列表,将其称为id
.
I have 2 lists of different objects (foo
& bar
) that share the same property lets call it id
.
public List<foo> foo { get; set; }
public List<bar> bar { get; set; }
我想从foo
中删除ID在bar
如何在linq中完成此操作?我一直在看Intersect
,RemoveAll
& Join
,但是找不到列表类型不同的任何示例.
How can this be done in linq? I have been looking at Intersect
, RemoveAll
& Join
but cannot find any example where the lists are of a different type.
尝试一下:
foo.RemoveAll(x=> !bar.Any(y=>y.Id==x.Id));
!bar.Any(y=>y.Id==x.Id)
将获得该项目是否在bar
集合中,如果不是,它将从foo
集合中将其删除.
!bar.Any(y=>y.Id==x.Id)
will get if item is in bar
collection and if it's not it will remove it from foo
collection.
使用哈希集O(n)的更好解决方案:
Better solution using hashset O(n):
var idsNotToBeRemoved = new HashSet<int>(bar.Select(item => item.Id));
foo.RemoveAll(item => !idsNotToBeRemoved.Contains(item.Id));
第二个答案的来源: https://stackoverflow.com/a/4037674/1714342
就像@Carra所说的那样,第一种解决方案对于小型列表是好的,第二种解决方案对于大型列表更有效.
as @Carra said, first solution is good for small lists and second is more efficient for big lists.