【问题标题】:Removing elements from binding list从绑定列表中删除元素
【发布时间】:2012-02-08 14:56:18
【问题描述】:

在我的一个项目中,我试图从 id 等于给定 id 的列表中删除一个项目。

我有一个名为UserListBindingList<T>

列表有RemoveAll()的所有方法。

因为我有一个BindingList<T>,所以我就这样使用它:

UserList.ToList().RemoveAll(x => x.id == ID )

但是,我的列表包含的项目数量与以前相同。
为什么它不起作用?

【问题讨论】:

    标签: c# wpf linq bindinglist


    【解决方案1】:

    它不起作用,因为您正在处理通过调用 ToList() 创建的列表的副本。

    BindingList<T> 不支持RemoveAll():它只是List<T> 功能,所以:

    IReadOnlyList<User> usersToRemove = UserList.Where(x => (x.id == ID)).
                                                 ToList();
    
    foreach (User user in usersToRemove)
    {
        UserList.Remove(user);
    }
    

    我们在这里调用ToList(),否则我们将在修改集合时枚举它。

    【讨论】:

      【解决方案2】:

      你可以试试:

      UserList = UserList.Where(x => x.id == ID).ToList(); 
      

      如果你在一个泛型类中使用RemoveAll(),你打算用来保存任何类型对象的集合,像这样:

      public class SomeClass<T>
      {
      
          internal List<T> InternalList;
      
          public SomeClass() { InternalList = new List<T>(); }
      
          public void RemoveAll(T theValue)
          {
              // this will work
              InternalList.RemoveAll(x =< x.Equals(theValue));
              // the usual form of Lambda Predicate 
              //for RemoveAll will not compile
              // error: Cannot apply operator '==' to operands of Type 'T' and 'T'
              // InternalList.RemoveAll(x =&amp;gt; x == theValue);
          }
      }
      

      此内容取自here

      【讨论】:

        【解决方案3】:

        如果绑定列表中只有一项作为唯一 ID,则下面的简单代码可以工作。

        UserList.Remove(UserList.First(x=>x.id==ID));
        

        【讨论】:

          猜你喜欢
          • 2022-11-14
          • 1970-01-01
          • 1970-01-01
          • 2017-03-05
          • 2014-12-19
          • 2013-11-25
          相关资源
          最近更新 更多