Collection ponderings...

BilboBaggins

New member
Joined
Oct 21, 2006
Messages
2
Programming Experience
5-10
I've got some code written by a developer no longer with us that has problems with For Each loops on collections that add/remove Objects to/from the collection.

In trying to resolve this issue it has brought to light my lack of understanding of Collections. So, in the interest of learning more about them, I thought I'd post my query and see if there is anyone out there smarter than I am.

Many of you probably already know where I'm going with this... The fore-mentioned loops blow up with the following exception:
Collection was modified; enumeration operation may not execute.

The code that causes the problem...
VB.NET:
For Each Member As MainDS.MembersRow In myDataClass.Members
    'Code that may add/remove items
Next

Suggested alternitive...
The code snippet below was shown for situations where items were being removed.
VB.NET:
For i as int32 = myDataClass.Members.Count-1 to 0 Step -1
    'Code that may remove items
Next

In reading a lot of googled material I found some answers but the details were seldom addressed. So here are a few questions...
  1. When you add an item to a Collection does it get added at the beginning or the end or is it arbitrary?
  2. As seen in that second example loop above. Will that work for a loop that may be adding and removing items to/from a collection?
  3. What is the best way to iterate through a collection when you are going to be adding/removing items while in the loop?
  4. Lastly... does anyone know of any good articles, threads or anything else that does a good job of explaining this subject in clear enough language that a confused person, like myself, could understand the why and how behind the answers to the previous questions?
That's all folks. Be gentle as you iterate through this post...
Thanks,
Jeff
 
Last edited:
The .Add method appends and .Insert method inserts. You can add (append) using the For (0 to collection.count) both forwards and backwards because the .Count property is only evaluated when the loop starts, so the loop will only iterate the original elements.

If you are removing while looping the collection you have to start with last element and step backwards.

You can't use the For Each enumerator if you intend to change the collection iterated.
 
Back
Top