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?
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);
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With