使用Linq从列表中删除与属性相交的项目 [英] Remove items from list that intersect on property using Linq

查看:61
本文介绍了使用Linq从列表中删除与属性相交的项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有2个共享相同属性的不同对象(foobar)的列表,将其称为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中完成此操作?我一直在看IntersectRemoveAll& 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.

这篇关于使用Linq从列表中删除与属性相交的项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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