Wednesday, 25 June 2008

Editing Collections

If you try to edit a collection using, say, a For...Each loop e.g.

For Each item in Collection.items
Next item

it's quite feasible to get an error which says you can't edit the collection you're iterating over while you're iterating over it. Which kind of makes sense.

The trick to doing it is to iterate over it backwards e.g.
Dim i As Integer
For i = Collection.Count To 0 Step -1
item = Collection.Item(i)
Next i

This way, you remove the items from the end of the collection, not the middle, which allows the .NET Runtime to keep track of the collection correctly.

(This might seem obvious to some but it held up some coding for me for about a month until a colleague made chance remark about it!)

No comments: