0

This is my original list:

var cart = _workContext.CurrentCustomer.ShoppingCartItems
                        .Where(sci => sci.ShoppingCartType == ShoppingCartType.ShoppingCart)
                        .LimitPerStore(_storeContext.CurrentStore.Id)
                        .ToList();

I reviewed this link : How do I change my new list without changing the original list?

And have understood that I have a method for copy so this is my method:

private List<ShoppingCartItem> CopyShoppingCartItems(List<ShoppingCartItem> target)
{
    //var tmp = new List<ShoppingCartItem>(target);
    var tmp = target.ToList();
    return tmp;
}

I test var var tmp = new List<shoppingCartItem>(target)too. this is my goal:

var beforeUpdatCart = CopyShoppingCartItems(cart);
foreach (var sci in cart)
{
    var remove = allIdsToRemove.Contains(sci.Id);
    if (remove)
        _shoppingCartService.DeleteShoppingCartItem(sci, ensureOnlyActiveCheckoutAttributes: true);
    else
    {
        foreach (var formKey in form.Keys)
            if (formKey.Equals($"itemquantity{sci.Id}", StringComparison.InvariantCultureIgnoreCase))
            {
                int newQuantity;
                if (int.TryParse(form[formKey], out newQuantity))
                {
                    sci.Quantity = newQuantity;
                }
                break;
            }
    }
}

but newQuantity is inserted in both List<shoppingCartItem> : cart and beforeUpdateCart.

Can any one help me?

Uwe Keim
  • 39,551
  • 56
  • 175
  • 291

1 Answers1

3

So you're actually changing the item in the list, not inserting the item into the list. While your lists are referencing different objects, they contain references on the same objects. That's why you get the item updated in both. Consider using deep copy to fix your issue. It may be done by creating copying constructor:

public ShoppingCartItem(ShoppingCartItem item)
{
    // copy all your fields there
}

And then:

private List<ShoppingCartItem> CopyShoppingCartItems(List<ShoppingCartItem> target)
{
    var tmp = target.ConvertAll(i => new ShoppingCartItem(i));
    return tmp;
}
Alex Riabov
  • 8,655
  • 5
  • 47
  • 48