How to Modify a Collection During Iteration in C#

Sometimes you’re going to find that you need to iterate over a collection like a List and make some modification while you’re in there.

It might look like this:

foreach (var item in list)
    if (item.Name == "Chris")
        list.Remove(item);

Seems easy enough, right? But doing this is going to give you a compiler error:
System.InvalidOperationException: Collection was modified; enumeration operation may not execute

So the question is, how do we get the same effect without getting the error? The trick is to copy the collection first.

var newList = List(sourceList);
foreach (var item in sourceList)
    if (item == "Chris")
        newList.Remove(item);
sourceList = newList;

Now there’s no longer an issue because the modification is done to the result collection and the collection being iterated over is never modified.

Advertisements

One thought on “How to Modify a Collection During Iteration in C#

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s