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++;
    }
}

About Bahrudin Hrnjica

PhD in Mechanical Engineering, Microsoft MVP for .NET. Likes .NET, Math, Mechanical Engineering, Evolutionary Algorithms, Blogging.

Posted on 03/12/2014, in .NET, C# and tagged , . Bookmark the permalink. 1 Comment.

  1. Nice and clean. :)

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