Collection was modified; enumeration operation may not execute

October 19, 2007

I came across this error today:

“Collection was modified; enumeration operation may not execute.”

Sounds nasty…actually very simple to solve. Problem was due to the collection I was looping (An arrayList) having an item removed mid-loop, which of course is going to screw up the enumeration. The solution is to create a copy of the collection, then use one for the Loop and one for your modifications:


Dim myArrayList as new arraylist
'Populate myArrayList here
Dim myArrayListforLooping as new arrayList(myArrayList)

Dim i As Integer = myArrayListforLooping.Count
Dim anItem as WhatEverObjectYourArrayListHolds

For Each anItem myArrayListforLooping
If (something = somethingelse) then
'Modify the collection, which doesnt effect our loop as
'we are looping using myArrayListforLooping
myArrayList.Remove(anItem)
End If
Next

Advertisements

One Response to “Collection was modified; enumeration operation may not execute”

  1. Aswath said

    thnx for yr post

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

%d bloggers like this: