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?
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 theRemoveAllmethod that takes in a predicate. You should also simplify your query like this: