Problem with deleting from Specialized Collection

sputnik75043

Member
Joined
Aug 28, 2010
Messages
13
Programming Experience
Beginner
my delete function uses:
myCol As System.Collections.Specialized.StringCollection

so, to delete from it, I use a for loop:
VB.NET:
        For i = 0 To myCol.Count - 1
            Dim myArr As String() = myCol(i).Split(",")

            If myArr(1) = name Then
                myCol.RemoveAt(i)
            End If
        Next

I've tried this in C#, and it works fine.
Let's say myCol.count starts at 7.
The problem is that, in VB.Net, as soon as you run the RemoveAt(i) function, the count of myCol becomes 6, so that when it reaches the last item in the loop, I get the following error:
Index was out of range. Must be non-negative and less than the size of the collection.

Any idea on how to get around this?
 
Last edited:
I figured it out - I just added 'Exit For' right after the myCol.RemoveAt(i)
That will work if you're only removing one item but if you need to remove multiple then you're still in the same boat. The way around this issue is to loop backwards, i.e. instead of this:
For i = 0 To myCol.Count - 1
you use this:
For i = myCol.Count - 1 To 0 Step -1
Because you start at the end and loop towards the beginning, removing an item does not affect the indexes of the items you are yet to examine.
 
Back
Top