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
The best way to remove items from a list while iterating over it is to use RemoveAll() .
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.
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.
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.
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)
You can't modify a collection while iterating it. Just use a normal for
loop instead of a foreach
loop.
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();
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
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