C# 从一个 List<T> 中删除在另一个 List<T> 中找到的元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9295483/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Remove elements from one List<T> that are found in another
提问by Wild Goat
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.
我想从 list1 中删除所有元素,这些元素也存在于 list2 中。当然,我可以遍历第一个循环以查找 list2 中的每个元素,但我正在寻找优雅的解决方案。
Thanks!
谢谢!
回答by Anthony Pegram
To change the actual list1 in place, you could use
要更改实际的 list1 到位,您可以使用
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 RemoveAllinvocation. If the list is small, don't worry about it. If you are unsure, test both ways and then you will know.
LukeH 在评论中提出了很好的建议。在第一个版本中,如果 list2 特别大,HashSet<T>在RemoveAll调用之前将列表加载到 a 中可能是值得的。如果列表很小,请不要担心。如果您不确定,请测试两种方式,然后您就会知道。
var theSet = new HashSet<YourType>(list2);
list1.RemoveAll(item => theSet.Contains(item));
回答by Massimiliano Peluso
list1.RemoveAll( item => list2.Contains(item));
回答by k.m
With LINQ:
使用 LINQ:
var result = list1.Except(list2);
回答by Mahmoud Gamal
Using LINQ you can do this:
使用 LINQ 你可以这样做:
List1.RemoveAll(i => !List2.Contains(i));
回答by dknaack
Description
描述
I think you mean the generic type List<Type>. You can use Linqto do this
我想你的意思是泛型类型List<Type>。您可以使用它Linq来执行此操作
Sample
样本
List<string> l = new List<string>();
List<string> l2 = new List<string>();
l.Add("one");
l.Add("two");
l.Add("three");
l2.Add("one");
l2.Add("two");
l2.Add("three");
l2.Add("four");
l2.RemoveAll(x => l.Contains(x));
More Information
更多信息
回答by Alexander R
var result = list1.Except(list2);
回答by romanoza
If you want to remove a list of objects (list2) from another list (list1) use:
如果list2要从另一个列表 ( list1) 中删除对象列表 ( ),请使用:
list1 = list1.Except(list2).ToList()
Remember to use ToList()to convert IEnumerable<T>to List<T>.
记得使用ToList()转换IEnumerable<T>为List<T>.
回答by Edev
var NewList = FirstList.Where(a => SecondList.Exists(b => b.ID != a.ID));
Using LINQ
使用 LINQ

