Loop collection and do changes

  • Thread starter Thread starter Fredrik Melin
  • Start date Start date
F

Fredrik Melin

The error I usally get is: Index out of range
(e.g. I removed a item in the collection, therefor my For I = 0 to
Col.count -1 gets invalid)

What I want to do is loop through a collection as it was, change the "real"
one (maybe add, remove)
So basically I would like to first copy a collection to a temporary, loop
through it, make changes to the original.


Is there any good way to do this? IClonable, or ?

Regards
Fredrik Melin
 
Hi Fredrik,
I asume it'is not a VB collection
(That goes from 1 to count).
The trick if you remove something is to do it reversal
as an example
for i = col.count -1 to 0 step -1
(This is when the index start on 0)
I hope this helps a little bit.
Cor
 
Fred if your using an enumerable collection and you 'change' elements inside
the for each loop, then you will generate this message. It is better to use
this.

For int x= collection.count -1 to 0 step -1

'Do operation with collection.item(x)

Next
 
Fredrik said:
The error I usally get is: Index out of range
(e.g. I removed a item in the collection, therefor my For I = 0 to
Col.count -1 gets invalid)

What I want to do is loop through a collection as it was, change the "real"
one (maybe add, remove)
So basically I would like to first copy a collection to a temporary, loop
through it, make changes to the original.


Is there any good way to do this? IClonable, or ?

you should make a _deep copy_ of your original collection.
then you can iterate the collection in for ... each loop.
ex.
cCopyCol=cOrigCol.Clone
for each oObj in cCopyCol
....
....
next

remeber to implement correct .clone method, because without this you'll
have _references_ to objects in cCopyCol collection.

jaro
 
Back
Top