Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Collection was modified; enumeration operation may not execute in ArrayList [duplicate]

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?

like image 910
Ricardo Avatar asked Jan 07 '10 22:01

Ricardo


2 Answers

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)

like image 91
Marc Gravell Avatar answered Oct 23 '22 12:10

Marc Gravell


Here's an example (sorry for any typos)

var itemsToRemove = new ArrayList();  // should use generic List if you can  foreach (var item in originalArrayList) {   if (...) {     itemsToRemove.Add(item);   } }  foreach (var item in itemsToRemove) {   originalArrayList.Remove(item); } 

OR if you're using 3.5, Linq makes the first bit easier:

itemsToRemove = originalArrayList   .Where(item => ...)   .ToArray();  foreach (var item in itemsToRemove) {   originalArrayList.Remove(item); } 

Replace "..." with your condition that determines if item should be removed.

like image 24
Will Avatar answered Oct 23 '22 10:10

Will