How to remove objects from an Enumerable collection in a loop

Posted by johnc on Stack Overflow See other posts from Stack Overflow or by johnc
Published on 2009-01-01T05:11:46Z Indexed on 2010/04/29 17:17 UTC
Read the original article Hit count: 473

Filed under:
|
|

Duplicate

Modifying A Collection While Iterating Through It


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)

For example, the following fails, as it modifies the List being enumerated over during the foreach

foreach (MyObject myObject in MyListOfMyObjects)
{
     if (condition) MyListOfMyObjects.Remove(myObject);
}

In the past I have used two methods.

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).

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.

These work fine, but neither feels nice, and I was wondering if anyone has come up with a more elegant solution to the issue

© Stack Overflow or respective owner

Related posts about .NET

Related posts about Patterns