title: How to remove objects from an Enumerable collection in a loop
body: <h2>Duplicate</h2>
  
  <p><a href="https://stackoverflow.com/questions/308466/modifying-a-collection-while-iterating-through-it-c">Modifying A Collection While Iterating Through It</a></p>
  
  <hr>
  
  <p>Has anyone a nice pattern to allow me to get around the inability to remove objects while I loop through an enumerable collection (eg, an IList or KeyValuePairs in a dictionary)</p>
  
  <p>For example, the following fails, as it modifies the List being enumerated over during the foreach</p>
  
  <pre><code>foreach (MyObject myObject in MyListOfMyObjects)
  {
       if (condition) MyListOfMyObjects.Remove(myObject);
  }
  </code></pre>
  
  <p>In the past I have used two methods.</p>
  
  <p>I have replaced the foreach with a reversed for loop (so as not to change the any indexes I am looping over if I remove an object).</p>
  
  <p>I have also tried storing a new collection of objects to remove within to loop, then looping through that collection and removed the objects from the original collection.</p>
  
  <p>These work fine, but neither <em>feels</em> nice, and I was wondering if anyone has come up with a more <em>elegant</em> solution to the issue</p>