Why the loop is not removing from the List all the items that are not starting with “CM”?

The problem is that you’re iterating forward through the list, while also removing items from it.

Let’s take an example

 0       1       2
[TopRig, TopRig, CM]

We enter the for loop, i = 0. We look at element 0, which is TopRig, so we call .RemoveAt(0). Our list is now:

 0       1
[TopRig, CM]

We now enter the next iteration of the for loop, and i is increment to 1. We look at element 1 of the (modified) list, and see that it’s CM.

See the problem? We skipped right over that second TopRig, because we removed an element from the list (causing all subsequent elements to be shifted backwards), and also increment i. We need to make sure that we only increment i if we don’t remove an item from the list:

for (int i = 0; i < Virtual.Count; /* no increment */)
{
    if (!Virtual[i].name.StartsWith("CM"))
        Virtual.RemoveAt(i);
    else
        i++;
}

or account for the fact that it will be incremented:

for (int i = 0; i < Virtual.Count; i++)
{
    if (!Virtual[i].name.StartsWith("CM"))
    {
        Virtual.RemoveAt(i);
        i--;
    }
}

You can also loop through the list backwards, which sidesteps the issue:

for (int i = Virtual.Count - 1; i >= 0; i--)
{
    if (!Virtual[i].name.StartsWith("CM"))
        Virtual.RemoveAt(i);
}

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top