Adding an element during enumeration

时间:2018-03-25 20:50:50

标签: c# .net

When the first condition doesn't satisfy because product is not already in the collection, it's then added via the else statement. However, when it is added - the foreach loop continues until all objects have been iterated - yet it never enters p._id == product._id and will continue to the else statement, adding another identical object.

May this be because I'm adding an element to a collection during enumeration? It's not actually added until enumeration is completed.

public void AddProduct(Product product)
{
    foreach(Product p in products)
    {
        if(p._id == product._id)
        {
            product._qty = product._qty + p._qty;
        }
        else
        {
            inventory.Add(p);
        }
    }
}

1 个答案:

答案 0 :(得分:0)

使用While循环或for循环,它不会抛出CollectionChangedException。