正在从绑定列表中删除元素

本文关键字:删除 元素 列表 绑定 | 更新日期: 2023-09-27 18:23:59

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

我有一个叫UserListBindingList<T>

列表具有所有方法RemoveAll()

由于我有一个BindingList<T>,我这样使用它:

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

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

正在从绑定列表中删除元素

它不起作用,因为您正在处理通过调用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(),因为否则我们将在修改集合时枚举它。

您可以尝试:

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);
    }
}

此内容取自此处。

如果bindinglist中只有一个项作为唯一ID,那么下面的简单代码就可以工作了。

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