What is the best way to remove list items in a loop in C #

Based on 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 a List object in a loop?

+6
source share
3 answers

There are several things that do not fit the loop approach, the main thing is that you cannot delete items from the collection that you are currently executing with foreach - you will get an exception.

Since your main collection is List<T> , you should use the RemoveAll method, which uses the predicate. You should also simplify your query as follows:

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

I do not think so. If you remove an item from the list in which you iterate, the results will be erroneous.

It is best to use the old form for the loop in reverse

 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); } } } 
+9
source

This is wrong (OP approach), as Steve correctly suggested (Steve way is probably the best in terms of performance),

I prefer to store 'those to be removed' in a separate list, then you can do this, for example.

 AllItems = AllItems.Except(Items2Remove); 

This is not best suited for performance, but for me it makes things cleaner - you can also combine with LINQ enumeration - for example. make IEnumerable from a list of records, etc.

hope this helps EDIT: just to clarify according to Steve's answer

+1
source

Source: https://habr.com/ru/post/913198/


All Articles