Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How best to remove list items in a loop in C#

Given the code:

var AllItems = new List<CartItem>();

using(var db = new MainContext())
{
    foreach (var item in AllItems)
    {
        if (!db.tblStoreItems.Where(i => i.ID == item.ItemID).Any())
        {
            AllItems.Remove(item);
        }
    }
}

Is this the best way to remove an item from the List object in a loop?

like image 338
Tom Gullen Avatar asked Apr 14 '12 12:04

Tom Gullen


1 Answers

I don't think so. If you remove an item from the list on which you are iterating, the results will be securely wrong.

It's best to use an old fashion for - loop in reverse order

using(var db = new MainContext()) 
{ 
    for(int x = AllItems.Count - 1; x >= 0; x--) 
    { 
        var item = AllItems[x];
        if (!db.tblStoreItems.Where(i => i.ID == item.ItemID).Any()) 
        { 
            AllItems.RemoveAt(x); 
        } 
    } 
}
like image 103
Steve Avatar answered Oct 02 '22 12:10

Steve