Changes made on “copy” list are reflecting original list - c#

后端 未结 3 394
终归单人心
终归单人心 2021-01-21 01:08

I have two lists, the original one and a copied one. I made a copy of the original list, because of one reason:

I need to process/work data from the original list, but I

相关标签:
3条回答
  • 2021-01-21 01:52

    You made a copy of the list, but the copy still contains references to the same objects; the objects themselves are not copied.

    0 讨论(0)
  • 2021-01-21 02:02

    You basicaly create shallow copy. It means it will copy all simple types, like references and generic types, but NOT objects content.

    As solution you need to totaly copy your objects:

    foreach (var itemss in forPrintKitchen)
    {
      forPrintKitchenOrders.Add(new OrderTemp(){ /*copy itemss here*/ });
    }
    

    I love to use AutoMapper for this task, but if you don't want to take framework in you project you can just implement IClonable on your OrderTemp type and all necessary nested types and call Clone() method.

    0 讨论(0)
  • 2021-01-21 02:10

    The collection that you are referring to as 'Copy List' is not actually a Copy.

    The elements inside the Collection are referring to the same Objects as in the Original Collection.

    You will have to replace your copying foreach loop with something like this:

    foreach (var item in forPrintKitchen)
    {
        forPrintKitchenOrders.Add(item.Clone()); // The clone method should return a new Instance after copying properties from item.
    }
    

    The Clone method should create new Instance and copy each of the properties from the instance being cloned and then return the newly created Instance.

    Basically you'll have to define a method named Clone (name doesn't matter) in OrderTemp class like this:

    public class OrderTemp
    {
        /*  other members of the class */
        public OrderTemp Clone()
        {
            return new OrderTemp
            {
                property1 = this.property1;
                property2 = this.property2;
                /* and so on */
            };
        }
    }
    
    0 讨论(0)
提交回复
热议问题