Remove items from a List while enumerating


Here is a simple way to remove items from currently enumerated list.
Put the list in while loop and make a manual index counter (var ind=0). Within while loop, every time items is removed decrease the index counter, otherwise increase the index.

private static void RemoveDirty(List<Element> lst)
{
    var ind = 0;
    while(ind<lst.Count)
    {
        var el= lst[ind];
        if (el.IsDirty)
        {
            lst.RemoveAt(ind);
            // in case item is removed decrease the index
            ind--;
        }
        // increase the index when nothing is happen
        ind++;
    }
}
Advertisement