Monday, March 27, 2006

Removing while iterating through a collection

Often times developers want to loop through a collection and filter out items. Unfortunatley they get the error that they can not change the contents while enumerating it. There are 2 solutions to this problem

1. Copy the records to be removed to an array or collection of some sort and then remove them in a second loop

2. Run it through a for loop backwards and remove the entries as needed

Dim refRow As dataRow
For i As Integer = ds.tables(0).Rows.Count - 1 To 0 Step -1
If ds.tables(0).rows(i).item("refundeeId") = refundeeId Then
End If

If we ran the loop forward instead of backwards and removed 10 out of 100 items when we got to the 90th iteration of the loop it would crash. This is because the size of the table has been reduced to 90 instead of 100 so when we try to access ds.tables(0).rows(91) it actually no longer exists.

By going backwards we are counting down and removing items. So if we removed 10 out of 100 again our table has only 90 records in it BUT we are now accessing ds.tables(0).rows(9) which still exists instead of try ds.tables(0).rows(91) which does not.

Hope that makes sense! :)


Post a Comment

<< Home