Remove item from ArrayList in a FOR loop (VB.NET)

Today I was trying to loop through an ArrayList (AL) that I had saved as a User Setting and remove values from the related AL that matched a specific value.  However, I was receiving the error, “Collection was modified; enumeration operation may not execute.”  This was because I was trying to remove an item from the AL while iterating through a For Each statement.

For Each str_env As String In My.Settings.Env_Collection

Dim env As Environment = GlobalVar.EnvCollection.ConvertStringToEnvironment(str_env)

If env.Division = div Then

My.Settings.Env_Collection.RemoveAt(i)

End If

i += 1

Next

To get around this, I tried switching over to a For statement instead, but received an Index Out of Bounds error because I used the original AL.Count() as my “stopping” point for the loop.  However, once I started removing items from the ArrayList, the Count() was less and there was no way to force my For loop to acknowledge that.  For example, if my initial Count() was 10 and I was removing 4 items, the For loop would continue up to 10 and not take into account any removed indexes; eventually, it would try to access an index that no longer existed in the ArrayList.

For i = 0 To My.Settings.Env_Collection.Count Step 1
Dim env As Environment = GlobalVar.EnvCollection.ConvertStringToEnvironment(My.Settings.Env_Collection(i))
If env.Division = div Then
My.Settings.Env_Collection.RemoveAt(i)
End If
Next

To resolve, simply step backwards through the array!

For i = (My.Settings.Env_Collection.Count – 1) To 0 Step1

Dim env As Environment = GlobalVar.EnvCollection.ConvertStringToEnvironment(My.Settings.Env_Collection(i))

If env.Division = div Then

My.Settings.Env_Collection.Remove(My.Settings.Env_Collection(i))

End If

Next

Simple, yet effective!  Happy coding!