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?

Answers


There are several things that are wrong with the loop approach, the main being - you cannot remove items from the collection you're currently iterating over with foreach - you will get an exception.

Since your main collection is a List<T>, you should use the RemoveAll method that takes in a predicate. You should also simplify your query like this:

AllItems.RemoveAll(item => !db.tblStoreItems.Any(i => i.ID == item.ItemID));

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

That's wrong (the OP's approach) as rightly suggested by Steve (Steve's way is probably the best in terms of performance),

I prefer to store the 'those to be removed' into a separate list, then you can do e.g.

AllItems = AllItems.Except(Items2Remove);  

That is not best from performance way but for me makes things cleaner - you could also combine with LINQ enumerate - e.g. make IEnumerable from the list of records etc.

hope this helps EDIT: just to clarify as per Steve's response


Need Your Help

How to get Google +1 count for current page in PHP?

php api google-api google-plus google-plus-one

I want to get count of Google +1s for current web page ? I want to do this process in PHP, then write number of shares or +1s to database. That's why, I need it. So, How can I do this process (gett...

what is different between type_gyroscope and type_gyroscope_uncalibrated?

android

In the Android 4.3, there are new sensors that are type_gyroscope_uncalibrated, magnetic_field_uncalibrated, game_rotation_vector, significant_motion.