2012-02-08 113 views
6

在我的一個項目中,我試圖從列表中刪除項目,其中id等於給定的id。我有一個的BindingList刪除綁定列表中的元素

UserList 

爲列表有一個方法

RemoveAll() 

爲Ia擁有的BindingList,所以我用這樣的

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

但是,這並不工作,我的列表中包含與以前相同數量的項目。爲什麼它不工作?

回答

11

它不起作用,因爲您正在處理通過調用ToList創建的列表的副本。

的BindingList不支持removeall過,這是一個列表功能而已,所以:

var itemToRemove = UserList.Where(x => x.id == ID).ToList(); 
foreach (var item in itemToRemove) 
{ 
    UserList.Remove(item); 
} 

需要調用ToList否則在修改它,我們將列舉的集合。

+0

@rafay我們需要ŧ o調用ToList,否則我們會在修改它時枚舉一個集合,這將引發異常。這是由於延遲執行Where。如果您使用副本,則當您調用RemoveAll時,原始列表(UserList)將不會更新。 – 2012-02-08 15:12:36

+0

謝謝。 – 2012-02-08 15:19:01

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

從MSDN評論:http://msdn.microsoft.com/en-us/library/wdka673a.aspx這個