Results 1 to 2 of 2

Thread: ArrayList problem

  1. #1

    Thread Starter
    Member leazfe's Avatar
    Join Date
    Mar 2004
    Location
    Spain
    Posts
    43

    ArrayList problem

    I have used an arrayList in order to avoid te capacity problems. But, i am getting the next error when i try to iterate over all elements:
    An unhandled exception of type 'System.InvalidOperationException' occurred in mscorlib.dll
    Additional information: Collection was modified; enumeration operation may not execute.
    The code is:
    Code:
    For Each tmpTree In ar
        If tmpTree.IsLeaf Then
           ar.Remove(tmpTree)
        End If
    Next
    The Message is enought clear, but really am I not able to modifie the arraylist?

    Thanks,
    Álvaro
    Last edited by leazfe; Apr 26th, 2004 at 09:34 AM.

  2. #2
    Fanatic Member pax's Avatar
    Join Date
    Mar 2001
    Location
    Denmark
    Posts
    840
    Hi.

    You can't use "For Each" on a collection, if you are going to remove items in that very collection.
    Simply because, it has no idea where to go next, cuz' you just removed it's reference.

    What you need to do is this :
    VB Code:
    1. For I= ar.Length-1 To 0 Step -1
    2.     tmpTree=ar(I)
    3.     If tmpTree.IsLeaf Then
    4.        ar.RemoveAt(I)
    5.     End If
    6. Next

    This will run through the collection backwards, removing as it goes. But because it's running backwards, and using an indexpointer, it still knows where to go next.

    Hope this clears things up a bit.
    I wish I could think of something witty to put in my sig...

    ...Currently using VS2013...

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width