Collection was modified; enumeration operation may not execute in ArrayList

Ricardo picture Ricardo · Jan 7, 2010 · Viewed 177.6k times · Source

I'm trying to remove an item from an ArrayList and I get this Exception:
Collection was modified; enumeration operation may not execute.

Any ideas?

Answer

Marc Gravell picture Marc Gravell · Jan 7, 2010

You are removing the item during a foreach, yes? Simply, you can't. There are a few common options here:

  • use List<T> and RemoveAll with a predicate
  • iterate backwards by index, removing matching items

    for(int i = list.Count - 1; i >= 0; i--) {
        if({some test}) list.RemoveAt(i);
    }
    
  • use foreach, and put matching items into a second list; now enumerate the second list and remove those items from the first (if you see what I mean)