从一个列表中的另一删除项目 [英] Remove items from one list in another

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

问题描述

我试图找出如何遍历,我想从项目的另一个列表中删除项目的通用的清单。

I'm trying to figure out how to traverse a generic list of items that I want to remove from another list of items.

所以,免得说我有这样一个假设的例子

So lest say I have this as a hypothetical example

List<car> list1 = GetTheList();
List<car> list2 = GetSomeOtherList();

我要遍历的List1在foreach并删除List1中其中也包含在列表2的每个项目。

I want to traverse list1 with a foreach and remove each item in List1 which is also contained in List2.

我不太清楚如何去,作为的foreach不是基于索引的。

I'm not quite sure how to go about that as foreach is not index based.

推荐答案

您可以使用除了

List<car> list1 = GetTheList();
List<car> list2 = GetSomeOtherList();
List<car> result = list2.Except(list1).ToList();

您可能甚至不需要那些临时变量:

You probably don't even need those temporary variables:

List<car> result = GetSomeOtherList().Except(GetTheList()).ToList();

注意除了不修改任意一个列表 - 它创造了一个新的列表,结果

Note that Except does not modify either list - it creates a new list with the result.

这篇关于从一个列表中的另一删除项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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