removing items from a generic List<t>

Posted by frosty on Stack Overflow See other posts from Stack Overflow or by frosty
Published on 2010-06-08T08:37:49Z Indexed on 2010/06/08 8:42 UTC
Read the original article Hit count: 200

Filed under:
|
|
|

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

© Stack Overflow or respective owner

Related posts about c#

Related posts about LINQ