首页 > 解决方案 > 如何使用 Any() 而不是 RemoveAll() 排除列表项?

问题描述

ListWithAllItems包含两种类型的项目:我要选择的项目和我不想选择的项目。

listForExcluding包含我应该排除的项目:

List<string> listForExcluding = ...;

所以我用两个字符串来做:

List<string> x = ListWithAllItems.ToList();

x.RemoveAll(p => listForExcluding.Any(itemForExclude => itemForExclude == p));

我如何使用Any()而不是RemoveAll()用一行来获取此查询?

标签: c#listlinqanyremoveall

解决方案


Any在这里没有意义,只需使用Except

var filtered = ListWithAllItems.Except(listForExcluding);

ToList如果你最后真的需要一个列表,否则不要无缘无故地意识到 IEnumerables (导致额外的枚举)。

如果您RemoveAll出于某种原因确实想要该版本,请使用Contains(这也是使用方法Where):

x.RemoveAll(p => listForExcluding.Contains(p));

还有许多其他有效的线路......但真的只是去Except


推荐阅读