Error when looping through a collection

Posted on 2006-07-13
Last Modified: 2012-05-05
I have a generic collection that I iterate through like so:

For Each module As IModule In moduleManager.instance
     '''Do something

In the loop I may or may not remove an item from the collection that I am looping through

So for example if I have one item in the collection and remove it then the loop continues (calling Enumerator.moveNext()) and it crashes with the error:
Collection was modified after the enumerator was instantiated.
 at System.Collection.Generic.LinkedList '1.Enumerator.MoveNext()

One way I can get around this is to do:
For Each module As IModule In moduleManager.instance
     '''Do something
     GoTo here

So that if something is removed I just start the loop again.

I don't like using GoTo statements and I have to unnecessarily loop through record that I already have looped through.

What can I do here instead?

Thanks a lot
Question by:se402036se
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 2
  • 2
  • 2
  • +1

Expert Comment

ID: 17100282
hi there,

Instead of using a for...each loop, use a loop based on the count of items in the collection.
Start the loop from the end and work backwards (step -1).
this will allow you to remove records from the collection inside the loop without procuding errors.

Hope to have helped.

Best Regards,
LVL 21

Expert Comment

ID: 17100284
Loop backwards through the collection using an index instead of foreach.

Author Comment

ID: 17100740
hmmm well the collection is defined as:

Private m_modules As Generic.LinkedList(Of IModule)

How can I loop through this collection using an index?

Something like:
For i As Integer = m_modules.count To 1 Step -1
   'But I cannot do m_modules(i)

as i get the error:
Class 'System.Collections.Generic.LinkedList(Of IModule)' cannot be indexed because it has no default property.

Any ideas?
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

LVL 21

Expert Comment

ID: 17101154
Ah, I missed the type of collection being used.  I'm still on the old framework so I'd just be guessing, but can't you do your own loop starting with an instance of LinkedListNode and stepping through the loop by calling Next on it?  This way, no iterator is in play so no code complains when you remove values from the linked list.
LVL 24

Accepted Solution

Jeff Certain earned 125 total points
ID: 17102221
You might try this type of approach

    Dim currentModule As LinkedListNode(Of IModule) =  m_modules.First
    Do While Not currentModule Is Nothing
      ' Do something
      currentModule = currentModule .Next

** Be careful that you relink all your nodes if you need to delete one

Author Comment

ID: 17107943
Thanks you gentlemen, I got it with:

 Dim currentModule As Generic.LinkedListNode(Of IModule) = getModuleList.First
        Dim nextModule As Generic.LinkedListNode(Of IModule)

        Do While Not currentModule Is Nothing
            nextModule = currentModule.Next
            'Do something
            currentModule = nextModule
LVL 24

Expert Comment

by:Jeff Certain
ID: 17107988
Glad I could help.

Featured Post

MS Dynamics Made Instantly Simpler

Make Your Microsoft Dynamics Investment Count  & Drastically Decrease Training Time by Providing Intuitive Step-By-Step WalkThru Tutorials.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This tutorial demonstrates one way to create an application that runs without any Forms but still has a GUI presence via an Icon in the System Tray. The magic lies in Inheriting from the ApplicationContext Class and passing that to Application.Ru…
Parsing a CSV file is a task that we are confronted with regularly, and although there are a vast number of means to do this, as a newbie, the field can be confusing and the tools can seem complex. A simple solution to parsing a customized CSV fi…
Finds all prime numbers in a range requested and places them in a public primes() array. I've demostrated a template size of 30 (2 * 3 * 5) but larger templates can be built such 210  (2 * 3 * 5 * 7) or 2310  (2 * 3 * 5 * 7 * 11). The larger templa…

734 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question