「RemoveAll」方法是最好的。
另一種常見的方法是:
var itemsToBeDeleted = collection.Where(i=>ShouldBeDeleted(i)).ToList();
foreach(var itemToBeDeleted in itemsToBeDeleted)
collection.Remove(itemToBeDeleted);
另一種常見的方法是使用「for」循環,但要確保你去向後:
for (int i = collection.Count - 1; i >= 0; --i)
if (ShouldBeDeleted(collection[i]))
collection.RemoveAt(i);
另一種常見的方法是添加的項目不是被刪除到一個新的集合:
var newCollection = new List<whatever>();
foreach(var item in collection.Where(i=>!ShouldBeDeleted(i))
newCollection.Add(item);
現在你有兩個集合。如果你想結束兩個集合,我特別喜歡的技術是使用不可變的數據結構。使用不可變的數據結構,「刪除」項目不會改變數據結構;它會給你一個新的數據結構(如果可能的話,它會重新使用舊數據結構中的數據),它沒有你刪除的項目。隨着不可變的數據結構你是不是修改你迭代的東西,所以沒有問題:
var newCollection = oldCollection;
foreach(var item in oldCollection.Where(i=>ShouldBeDeleted(i))
newCollection = newCollection.Remove(item);
或
var newCollection = ImmutableCollection<whatever>.Empty;
foreach(var item in oldCollection.Where(i=>!ShouldBeDeleted(i))
newCollection = newCollection.Add(item);
當你做,你有兩個集合。新的物品被刪除,舊的和以前一樣。
可能重複的[如何有條件地從.NET集合中刪除項目](http://stackoverflow.com/questions/653596/how-to-conditionally-remove-items-from-a-net-收集) – 2012-01-09 17:29:21