c# - 如何使用 Any() 而不是 RemoveAll() 排除列表项?
问题描述
ListWithAllItems
包含两种类型的项目:我要选择的项目和我不想选择的项目。
listForExcluding
包含我应该排除的项目:
List<string> listForExcluding = ...;
所以我用两个字符串来做:
List<string> x = ListWithAllItems.ToList();
x.RemoveAll(p => listForExcluding.Any(itemForExclude => itemForExclude == p));
我如何使用Any()
而不是RemoveAll()
用一行来获取此查询?
解决方案
Any
在这里没有意义,只需使用Except
:
var filtered = ListWithAllItems.Except(listForExcluding);
ToList
如果你最后真的需要一个列表,否则不要无缘无故地意识到 IEnumerables (导致额外的枚举)。
如果您RemoveAll
出于某种原因确实想要该版本,请使用Contains
(这也是使用方法Where
):
x.RemoveAll(p => listForExcluding.Contains(p));
还有许多其他有效的线路......但真的只是去Except
推荐阅读
- spring-boot - 基于活动配置文件测试条件初始化的 RestController
- typo3 - TYPO3 9 - 子页面上的站点定义
- c - 当我们使用while循环时找出程序的复杂性
- python - 将瞬间列表转换为增量列表
- tensorflow - 多类逻辑回归 Tensorflow 2.0
- r - Flexdashboard 宽表滚动到侧边栏
- ruby-on-rails - `fork':Bootsnap::LoadPathCache::FallbackScan 在 Manjaro 上运行 `rails console`
- reactjs - 使用 ref React 将子组件的高度更改为父组件的高度
- c++ - 如何在没有空格的情况下读取 C++ 中的值?
- javascript - 从我的反应原生应用程序中打开苹果指南针应用程序