Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/wpf/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/303.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 从绑定列表中删除元素_C#_Wpf_Linq_Bindinglist - Fatal编程技术网

C# 从绑定列表中删除元素

C# 从绑定列表中删除元素,c#,wpf,linq,bindinglist,C#,Wpf,Linq,Bindinglist,在我的一个项目中,我试图从id等于给定id的列表中删除一项 我有一个名为UserList的BindingList 列表包含所有方法RemoveAll() 因为我有一个绑定列表,所以我这样使用它: UserList.ToList().RemoveAll(x => x.id == ID ) 但是,我的列表包含的项目数与以前相同。 为什么它不工作?它不工作是因为您正在处理通过调用ToList()创建的列表副本 BindingList不支持RemoveAll():它只是一个List功能,因此:

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

我有一个名为
UserList
BindingList

列表包含所有方法
RemoveAll()

因为我有一个
绑定列表
,所以我这样使用它:

UserList.ToList().RemoveAll(x => x.id == ID )
但是,我的列表包含的项目数与以前相同。

为什么它不工作?

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

BindingList
不支持
RemoveAll()
:它只是一个
List
功能,因此:

IReadOnlyList<User> usersToRemove = UserList.Where(x => (x.id == ID)).
                                             ToList();

foreach (User user in usersToRemove)
{
    UserList.Remove(user);
}
IReadOnlyList usersToRemove=UserList.Where(x=>(x.id==id))。
托利斯特();
foreach(usersToRemove中的用户)
{
UserList.Remove(用户);
}
我们在这里调用
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);
    }
}
公共类SomeClass
{
内部列表内部列表;
public SomeClass(){InternalList=new List();}
public void RemoveAll(T值)
{
//这会奏效的
RemoveAll(x=

此内容取自。

如果bindinglist中只有一项作为唯一ID,下面的简单代码可以工作

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