This question already has an answer here:
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?
This question already has an answer here:
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?
Instead of foreach(), use a for() loop with a numeric index.
You are removing the item during a
foreach
, yes? Simply, you can't. There are a few common options here:List<T>
andRemoveAll
with a predicateiterate backwards by index, removing matching items
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)Don't modify the list inside of a loop which iterates through the list.
Instead, use a
for()
orwhile()
with an index, going backwards through the list. (This will let you delete things without getting an invalid index.)One way is to add the item(s) to be deleted to a new list. Then go through and delete those items.
using
ArrayList
also you can try like thisI like to iterate backward using a
for
loop, but this can get tedious compared toforeach
. One solution I like is to create an enumerator that traverses the list backward. You can implement this as an extension method onArrayList
orList<T>
. The implementation forArrayList
is below.The implementation for
List<T>
is similar.The example below uses the enumerator to remove all even integers from an
ArrayList
.