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

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

问题描述

我想弄清楚如何遍历我想从另一个项目列表中删除的通用项目列表.

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

假设我有这个例子

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

我想用 foreach 遍历 list1 并删除 List1 中的每个项目,该项目也包含在 List2 中.

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();

请注意,Except 不会修改任何一个列表 - 它会使用结果创建一个新列表.

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

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

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