在我的一个项目中,我试图从列表中删除项目,其中id等于给定的id。我有一个的BindingList删除绑定列表中的元素
UserList
为列表有一个方法
RemoveAll()
为Ia拥有的BindingList,所以我用这样的
UserList.ToList().RemoveAll(x=>x.id==ID)
但是,这并不工作,我的列表中包含与以前相同数量的项目。为什么它不工作?
在我的一个项目中,我试图从列表中删除项目,其中id等于给定的id。我有一个的BindingList删除绑定列表中的元素
UserList
为列表有一个方法
RemoveAll()
为Ia拥有的BindingList,所以我用这样的
UserList.ToList().RemoveAll(x=>x.id==ID)
但是,这并不工作,我的列表中包含与以前相同数量的项目。为什么它不工作?
它不起作用,因为您正在处理通过调用ToList创建的列表的副本。
的BindingList不支持removeall过,这是一个列表功能而已,所以:
var itemToRemove = UserList.Where(x => x.id == ID).ToList();
foreach (var item in itemToRemove)
{
UserList.Remove(item);
}
需要调用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 =&gt; x == theValue);
}
}
从MSDN评论:http://msdn.microsoft.com/en-us/library/wdka673a.aspx这个
@rafay我们需要ŧ o调用ToList,否则我们会在修改它时枚举一个集合,这将引发异常。这是由于延迟执行Where。如果您使用副本,则当您调用RemoveAll时,原始列表(UserList)将不会更新。 – 2012-02-08 15:12:36
谢谢。 – 2012-02-08 15:19:01