从列表中删除不常见的项目 [英] Remove non-common items from list

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

问题描述

我有两个对象列表,其中一个具有不同数量的项目.现在,如果我这样做:

I have two list of objects one of which has a different number of items. Now, if I do a:

 var result = list1.Except(list2);

那会给我list1而不是list2中的项目之间的区别,对吗?如果可能的话,我想做的就是在同一步骤中将所有这些项从list1中删除. 我不想做的是必须遍历结果"列表并将其从list1中删除.有可能吗?

That would give me the difference between the items that are in list1 and not in list2, right? What I'd like to do, if possible, is to remove from list1 all those items in the same step. What I don't want to do is to have to loop through the "result" list and remove them from list1. Is that possible?

谢谢!

推荐答案

您可以使用List.RemoveAll:

list1.RemoveAll(t => !list2.Contains(t));

这不需要创建新的集合,也只需要一个循环即可删除list1中但list2中没有的所有项目.但是,我认为您误解了LINQ的工作原理. Enumerable.Except是使用延迟执行实现的.这意味着直到foreach才会执行它. Except对于大型列表也非常有效,因为它使用的是固定方法.

This does not need to create a new collection and it also needs only one loop to remove all items that are in list1 but not in list2. However, i assume that you have misunderstood how LINQ works. Enumerable.Except is implemented using deferred execution. That means it will not be executed until the foreach. Except is also very efficient with large lists since it's using a set approach.

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

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