Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>The "RemoveAll" method is best.</p> <p>Another common technique is:</p> <pre><code>var itemsToBeDeleted = collection.Where(i=&gt;ShouldBeDeleted(i)).ToList(); foreach(var itemToBeDeleted in itemsToBeDeleted) collection.Remove(itemToBeDeleted); </code></pre> <p>Another common technique is to use a "for" loop, but make sure you go <em>backwards</em>:</p> <pre><code>for (int i = collection.Count - 1; i &gt;= 0; --i) if (ShouldBeDeleted(collection[i])) collection.RemoveAt(i); </code></pre> <p>Another common technique is to add the items that are <em>not</em> being removed to a new collection:</p> <pre><code>var newCollection = new List&lt;whatever&gt;(); foreach(var item in collection.Where(i=&gt;!ShouldBeDeleted(i)) newCollection.Add(item); </code></pre> <p>And now you have two collections. A technique I particularly like if you want to end up with two collections is to use immutable data structures. With an immutable data structure, "removing" an item does not change the data structure; it gives you back a new data structure (that re-uses bits from the old one, if possible) that does not have the item you removed. With immutable data structures you are not modifying the thing you're iterating over, so there's no problem:</p> <pre><code>var newCollection = oldCollection; foreach(var item in oldCollection.Where(i=&gt;ShouldBeDeleted(i)) newCollection = newCollection.Remove(item); </code></pre> <p>or</p> <pre><code>var newCollection = ImmutableCollection&lt;whatever&gt;.Empty; foreach(var item in oldCollection.Where(i=&gt;!ShouldBeDeleted(i)) newCollection = newCollection.Add(item); </code></pre> <p>And when you're done, you have two collections. The new one has the items removed, the old one is the same as it ever was.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload