【问题标题】:SortableSearchableList<T> RemoveAll doesn't workSortableSearchableList<T> RemoveAll 不起作用
【发布时间】:2016-01-22 04:01:54
【问题描述】:

我正在尝试使用 lambda 表达式根据其他列表中的值从列表中删除某个对象。这是我的代码:

List<Client> clientsList = GetSomeList();

SortableSearchableList<Client> clients = new SortableSearchableList<Client>(clientsList);
clients.ToList().RemoveAll(x=> lstPostalCodes.Any(c => c.City.PostalCode == x.PostalCode && c.SubId == x.SubId));

当我使用 RemoveAll 方法时,表示删除了一定数量的项目,但实际上没有。

【问题讨论】:

  • 调用 ToList() 后,您将获得一个新列表,RemoveAll() 正在对其进行操作。您可能希望在 SortableSearchableList 类上实现自己的 RemoveAll()。

标签: c# list generics collections


【解决方案1】:

您正在创建一个新列表,使用 clients 中的项目填充它,然后您将遍历该新列表中的项目并删除与您的条件匹配的项目,然后您将把那个新清单丢在地上,再也不用它了。您不会将它存储在任何地方,或者以任何方式使其可以被以后的代码接受。

如果您希望 clients 中的项目发生变化,那么您需要从该集合中移除项目,而不是创建一个新集合并从该新集合中移除项目。

【讨论】:

    【解决方案2】:

    我是这样解决的:

    List<Client> clientsList = GetSomeList();
    clientsLists.RemoveAll(x=> lstPostalCodes.Any(c => c.City.PostalCode == x.PostalCode && c.SubId == x.SubId));
    
    SortableSearchableList<Client> clients = new SortableSearchableList<Client>(clientsList);
    

    在创建 SortableSearchableList 之前从列表中删除项目

    【讨论】:

      猜你喜欢
      • 2016-04-01
      • 2021-01-08
      • 1970-01-01
      • 1970-01-01
      • 2015-04-24
      • 2020-06-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多