|
-
Jul 1st, 2009, 12:46 PM
#1
Thread Starter
Hyperactive Member
[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 
-
Jul 1st, 2009, 01:00 PM
#2
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
-
Jul 1st, 2009, 01:28 PM
#3
Thread Starter
Hyperactive Member
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
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|