Tuesday, April 05, 2005 11:46:49 PM UTC :: Filed Under ASP.NET | VB.NET

It seems easier than it is… looping through an array of items (collection) and removing items you don’t want.  However, when you remove an item from a collection while looping through it, the size of the collection changes and the loop may fail… depending on how you are looping.

The correct way to loop through a collection is to essentially loop through it backwards, starting with the item with the maximum ID and working down to zero:

    1  For i As Integer = MyList.Count - 1 To 0 Step -1
    2      If MyList.Items(i).Value <> SomeValue Then
    3          MyList.Remove(MyList(i))
    4      End If
    5  Next
Comments are closed.
Navigation
On this page....
Search
Archives
<July 2010>
SunMonTueWedThuFriSat
27282930123
45678910
11121314151617
18192021222324
25262728293031
1234567
Categories
Contact me
Send mail to the author(s) Contact Todd M. Taylor