Deletion of List Items While Looping


Peace be upon you,

There is a very popular logical bug when you are looping on a list to delete some of its items when a certain condition is satisfied, we would think of the algorithm to be like this:

for (int i = 0; i < list.Items.Count; i++)
{

if (condition)
list.Items.Delete(list.Items[i])

}

Unfortunately that won’t delete all the items satisfying the condition, because on deletion of an item we are changing the list structure by shifting the items to fill the gab caused by the item deleted while still advancing our index, so the item after the one we are deleting will be skipped.

Now how to solve this, it’s simple just don’t increase the index on item deletion like follows

for (int i = 0; i < list.Items.Count; i++)
{

if (condition)
{
list.Items.Delete(list.Items[i]);
i- -;
}

}

Happy Programming 🙂

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s