2010-01-25 35 views
3

我正在開發Silverlight 2/3應用程序。我想使用List.RemoveAll(或者它的IList.RemoveAll?)並指定謂詞,以便我可以在一次掃描中從列表中移除一堆元素。儘管如此,Silverlight中似乎並不存在這個函數。我在這裏錯過了什麼嗎?有沒有其他方法同樣簡單?現在,我在foreach中手動迭代我的元素並保留第二個列表(因爲迭代時不能刪除),而且非常麻煩。列表<T> .RemoveAll不存在於Silverlight中?

+0

p.S.從http://stackoverflow.com/questions/308466/how-to-modify-or-delete-items-from-an-enumerable-collection-while-iterating-throu – ashes999 2010-01-25 18:10:49

回答

3

如果你真正需要的是訪問該子集,則有真的沒有理由去除,只是像這樣訪問子集:

而不是(可能:

List<string> subSet = l.RemoveAll (p => !p.StartsWith ("a")); 

剛剛獲得逆:

List<string> l = new List<string>() { "a", "b", "aa", "ab" }; 
var subSet = l.Where (p => p.StartsWith ("a")); 


OK,但要真正刪除它們(假設與上面相同的首發名單):

l.Where (p => p.StartsWith ("a")).ToList().ForEach (q => l.Remove (q)); 

。哪裏是IEnumerable的擴展方法,在System.Linq中。 所以只要你的列表是一個通用的IEnumerable(你已經添加了使用)它應該是可用的。

+0

這正是問題所在; l.RemoveAll和l.Where不存在並拋出編譯錯誤。這就是我想解決的問題... 我真的* *需要刪除它們:) – ashes999 2010-01-25 19:22:47

+0

那些肯定存在,最後的代碼片段將做到這一點,我編譯並運行在Silverlight應用程序之前寫這個:) – Bobby 2010-01-25 19:38:53

+0

令人討厭的是,他們放棄了RemoveAll,但我想幫助瘦客戶機框架。 – Bobby 2010-01-25 19:46:20

3

你可以使用LINQ像:

list = list.Where(predicate).ToList(); 

的另一種方法是刪除的元素在for循環中:

for (int i = list.Count - 1; i >= 0; --i) 
    if (predicate(list[i])) 
     list.RemoveAt(i); 
+0

我得到了一個編譯錯誤類似於: System.Collections.Generic.IList '不包含'Where'的定義,也沒有'Where'的擴展方法... – ashes999 2010-01-25 19:24:00

+1

@ ashes999:確保在源文件的頂部有一個'using System.Linq;'。另外,確保你的項目中引用了'System.Core'。我在Silverlight 3中測試了它,它應該可以工作。 – 2010-01-25 19:31:24

+0

正是我想要的解決方案 - 使用System.Linq! – ashes999 2010-01-25 19:55:28

2

我與Mehrdad就此而言,一種擴展方法可以解決這個問題。給你的完整簽名,這裏是:

/// <summary> 
    /// Removes all entries from a target list where the predicate is true. 
    /// </summary> 
    /// <typeparam name="T">The type of item that must exist in the list.</typeparam> 
    /// <param name="list">The list to remove entries from</param> 
    /// <param name="predicate">The predicate that contains a testing criteria to determine if an entry should be removed from the list.</param> 
    /// <returns>The number of records removed.</returns> 
    public static int RemoveAll<T>(this IList<T> list, Predicate<T> predicate) 
    { 
     int returnCount = 0; 

     for (int i = list.Count - 1; i >= 0; --i) 
     { 
      if (predicate(list[i])) 
      { 
       list.RemoveAt(i); 
       returnCount++; 
      } 
     } 

     return returnCount; 
    } 
相關問題