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...
Suggested alternitive...
The code snippet below was shown for situations where items were being removed.
In reading a lot of googled material I found some answers but the details were seldom addressed. So here are a few questions...
Thanks,
Jeff
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...
- When you add an item to a Collection does it get added at the beginning or the end or is it arbitrary?
- 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?
- What is the best way to iterate through a collection when you are going to be adding/removing items while in the loop?
- 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?
Thanks,
Jeff
Last edited: