Getting InvalidOperationException when I modify an arraylist
-
foreach (myobject value in copy){ ... copy.RemoveAt(copy.IndexOf(value)); ... } The first iteration works okay, but when the loop starts again, it throws and InvalidOperationException. Any thoughts as to how I can remove an element within the arraylist whilst still using the same list?
-
foreach (myobject value in copy){ ... copy.RemoveAt(copy.IndexOf(value)); ... } The first iteration works okay, but when the loop starts again, it throws and InvalidOperationException. Any thoughts as to how I can remove an element within the arraylist whilst still using the same list?
Hi, I see two ways to get rid of it: 1. use a second ArrayList: 1a. if only a few to remove, store the indices to be removed in another empty ArrayList, then in a second loop, remove those (warning: indices change while removing, so best do the second loop backwards) 1b. if most of them to be removed, start a new ArrayList and copy the items you want to keep, then throw away the original ArrayList OR 2. don't use foreach, instead use a for loop that runs backwards (or compensate for the indices changing when removing). :)
Luc Pattyn [Forum Guidelines] [My Articles]
this months tips: - use PRE tags to preserve formatting when showing multi-line code snippets - before you ask a question here, search CodeProject, then Google
-
foreach (myobject value in copy){ ... copy.RemoveAt(copy.IndexOf(value)); ... } The first iteration works okay, but when the loop starts again, it throws and InvalidOperationException. Any thoughts as to how I can remove an element within the arraylist whilst still using the same list?
humblepgmr wrote:
foreach (myobject value in copy){ ... copy.RemoveAt(copy.IndexOf(value)); ... }
Hi there, There was some information at Microsoft about this. You might consider checking out http://support.microsoft.com/kb/555972 to read about it. Looks like a workaround involves creating a copy of the collection within the foreach loop. Good Luck!
You can't teach people to be lazy - either they have it, or they don't. -Dagwood Bumbstead