Results 1 to 3 of 3

Thread: [RESOLVED] Erasing Items in A Collection Using a Loop

  1. #1

    Thread Starter
    Hyperactive Member neef's Avatar
    Join Date
    Dec 2001
    Location
    Boston
    Posts
    311

    [RESOLVED] Erasing Items in A Collection Using a Loop

    I often use a for/next loop to cycle through a collection to find a particular member of that collection based on some criteria. This works fine in every case except one: when I want to then erase the very member of the collection I just found. For example, if I wanted to give the heave-ho to every obect in a collection class that has a member veriable Color equal to Red:
    Code:
    dim x as byte
    for x=0 to m_CollectionOfSomething.Count-1
         if m_CollectionOfSomething.Color = Color.Red then
              m_CollectionOfSomething.Erase(x)
         end if
    next
    The problem is once the collection class member is erased it makes to loop invalid because taking out the member reduces the total count of the collection in the middle of the loop. Eventually I get a "Index is out of range" error.

    This circumstance has bothered me every so often; I bet more experienced programmers have a different type of loop system that works better than this when you want to erase a collection member.

    Hope I explained this well enough and thanks!
    Last edited by neef; Jul 1st, 2009 at 01:30 PM.
    Intermediate Level Programmer Extraordinaire

  2. #2
    PowerPoster keystone_paul's Avatar
    Join Date
    Nov 2008
    Location
    UK
    Posts
    3,327

    Re: Erasing Items in A Collection Using a Loop

    Simple - you work backwards...

    Code:
    For x = m_collectionofsomething.count-1 to 0 step -1
        if m_CollectionOfSomething.Color = Color.Red then
              m_CollectionOfSomething.Erase(x)
         end if
    Next

  3. #3

    Thread Starter
    Hyperactive Member neef's Avatar
    Join Date
    Dec 2001
    Location
    Boston
    Posts
    311

    Re: Erasing Items in A Collection Using a Loop

    So simple it's brilliant! Thanks so much!

    I wish i asked this question a year ago.
    Intermediate Level Programmer Extraordinaire

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