Error: C# Collection was modified; enumeration operation may not execute

http://stackoverflow.com/questions/2024179/c-collection-was-modified-enumeration-operation-may-not-execute

Simple solution is: When you get this error, don’t you foreach instead use for loop for collections.

Problem: I’m trying to remove a item from a ArrayList and I get this Exception:
Collection was modified; enumeration operation may not execute.
Any ideas? thanks for the help

Solution:

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)

For the record, unless you are using .NET 1.0 or 1.1, you should probably be using List<T> instead of ArrayList. – Marc Gravell♦ Jan 7 ’10 at 22:37

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s