删除从一个列表&LT元素; T>这在另一个发现 [英] Remove elements from one List<T> that are found in another

查看:128
本文介绍了删除从一个列表&LT元素; T>这在另一个发现的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个名单

 列表< T> list1的=新的List< T>(); 
名单< T>列表2 =新的List< T>();



我想删除所有的List1元素,这也存在列表2。当然,我可以循环通过第一循环寻找list2中每一个元素,但是我正在寻找优雅的解决方案。



谢谢!


< DIV CLASS =h2_lin>解决方案

要更改实际的List1的地方,你可以使用

  list1.RemoveAll(项目=> list2.Contains(项目)); 

您可能会改为宁愿只需在列表中查询,而无需修改任何

  VAR的结果= list1.Except(列表2); 



LukeH使得在评论一个很好的建议。在第一个版本,如果列表2是特别大,它可能是值得列表加载到的HashSet< T> 之前的 removeall过调用。如果列表是小,不担心。如果你不确定,测试两种方式,然后你就知道了。



  VAR theSet =新的HashSet< YourType>(列表2); 
list1.RemoveAll(项目=> theSet.Contains(项目));


I have two lists

 List<T> list1 = new List<T>();
 List<T> list2 = new List<T>();

I want remove all elements from list1, which also exist in list2. Of course I can loop through the first loop looking for each element in list2, but I am looking for elegant solution.

Thanks!

解决方案

To change the actual list1 in place, you could use

list1.RemoveAll(item => list2.Contains(item));

You might instead prefer to simply have a query over the lists without modifying either

var result = list1.Except(list2);

LukeH makes a good recommendation in the comments. In the first version, and if list2 is particularly large, it might be worth it to load the list into a HashSet<T> prior to the RemoveAll invocation. If the list is small, don't worry about it. If you are unsure, test both ways and then you will know.

var theSet = new HashSet<YourType>(list2);
list1.RemoveAll(item => theSet.Contains(item));

这篇关于删除从一个列表&LT元素; T&GT;这在另一个发现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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