Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

removing items from a generic List<t>

I have the following method, I wish to remove items from my collection that match the product Id. Seems fairly straight forward, but i get an exception. Basically my collection is getting out of sync. So what is the best way to remove an item from a collection.

public void RemoveOrderItem(Model.Order currentOrder, int productId)
{

    foreach (var orderItem in currentOrder.OrderItems)
    {
        if (orderItem.Product.Id == productId)
        {
            currentOrder.OrderItems.Remove(orderItem);
        }
    }
}

Exception Details: System.InvalidOperationException: Collection was modified; enumeration operation may not execute

like image 733
frosty Avatar asked Jun 08 '10 08:06

frosty


People also ask

How do you remove an element from a generic list while iterating over it?

The best way to remove items from a list while iterating over it is to use RemoveAll() .

What method do you use to remove an item from a list t at a specific index?

RemoveAt (Int32) Method is used to remove the element at the specified index of the List<T>. Properties of List: It is different from the arrays.

How do I remove an item from a list in Uipath?

RemoveAt where you need to provide the index value of a list which you need to remove that value. Here i provided the input argument index value as 0. So, it will remove the first value which is added in the list. This is how you can remove value a particular value from a list by providing the index value.

How do I remove an item from an object list?

The remove(Object obj) method of List interface in Java is used to remove the first occurrence of the specified element obj from this List if it is present in the List.


4 Answers

Modifying a collection inside a loop doesn’t work. To work around that, List has a few methods that allow “batch” modifications of a collection. In your case, use:

currentOrder.OrderItems.RemoveAll(x => x.Product.Id == productId)
like image 59
Konrad Rudolph Avatar answered Oct 17 '22 06:10

Konrad Rudolph


You can't modify a collection while iterating it. Just use a normal for loop instead of a foreach loop.

like image 29
Hans Olsson Avatar answered Oct 17 '22 05:10

Hans Olsson


By looping this way you can not remove items because its in collection it keeps the track of the stored items.

Easy way to do this :

   authorsList.RemoveAll(x => x.ProductId == productId);

or

   authorsList = authorsList.Where(x => x.ProductId!= productId).ToList();
like image 45
Pranay Rana Avatar answered Oct 17 '22 07:10

Pranay Rana


You can't remove an item from a collection you are iterating through, you could keep track of the orderItem, then remove it after you finish looping

like image 33
BenW Avatar answered Oct 17 '22 06:10

BenW