Thursday, October 23, 2008

A common scenario is wanting to delete an item while iterating over a collection using foreach:

foreach (string name in names)

{

    if (name == "Kirk")

    {

        names.Remove(name);

    }

}

Unfortunately, this will give the dreaded InvalidOperationException:

Collection was modified; enumeration operation may not execute.

This is because modifying the state of a collection invalidates the enumerator that foreach uses behind the scenes to loop over the collection.

A common work-around is to convert the foreach to a for loop:

for (int i = names.Count - 1; i >= 0; i--)

{

    if (names[i] == "Kirk")

    {

        names.RemoveAt(i);

    }

}

You'll notice that the for loop goes backwards from the end of the list (position: Count - 1) back to the start (position: 0), so that when an item is removed, our current index i is still a valid position in the list.

How do you do it?

Kirk

Source (such that it is) Program.txt

All comments require the approval of the site owner before being displayed.
Name
E-mail
Home page

Comment (HTML not allowed)