Removing Items from a Collection - Please Help
Hi There
Please see my code below:
VB Code:
Dim tiIndex As Integer
For tiIndex = 0 To colTIData.Count - 1
If colTIData(tiIndex).tiKey = Id Then
colTIData.Remove(tiIndex)
End If
Next
I have 4 items in my collection. The first 2 items meet the condition, and I expect to have them removed, and at the end remain with 2.
Now, when I run this code, Item 1 is removed & colTHdata.count becomes 3, but Item 2 is not. When tiIndex is 3, I get the following error:
An unhandled exception of type 'System.ArgumentOutOfRangeException' occurred in mscorlib.dll
Additional information: Specified argument was out of the range of valid values.
I can understand getting the error, since when I deleted Item1, Count was reduced from 4 to 3, and the statement:
VB Code:
For tiIndex = 0 To colTIData.Count - 1
is referring to the original count of 4.
To avoid the error, I had to include the following statement:
VB Code:
If tiIndex >= colTIData.Count - 1 Then
Exit For
End If
However, that doesn't solve my problem of wanting to remove 2 items
How do I make sure that ALL ITEMS MEETING THE CONDITION ARE REMOVED FROM THE COLLECTION?
Please help.