Saturday, January 24, 2009

Removing items from list while looping through

Here is a sample code which lets you remove the items dynamically from the list.

List listObj = new List();
int count = 0;
while (count < listObj.Count)
{
if (conditionToRemove)
{
listObj.RemoveAt(count);
count--;
}
count++;
}

Whenever we make a call to RemoveAt or Remove function of list within a loop where the loop index tracks the Count of the list object, the loop index should also be decremented. Otherwise the code will throw IndexOutOfRange exception.

Consider the following line of code..

for (int i = 0; i < listObj.Count; i++)
{
listObj.RemoveAt(i);
}

this code will throw IndexOutOfRange exception as the Count of the List will be dynamically changing(decreasing) but the index of the for loop is incrementing.