Hi There

Please see my code below:

VB Code:
  1. Dim tiIndex As Integer
  2. For tiIndex = 0 To colTIData.Count - 1
  3.       If colTIData(tiIndex).tiKey = Id Then
  4.           colTIData.Remove(tiIndex)
  5.       End If  
  6.  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:
  1. 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:
  1. If tiIndex >= colTIData.Count - 1 Then
  2.                     Exit For
  3.                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.