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

后端 未结 3 436
终归单人心
终归单人心 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 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 */
            };
        }
    }
    

提交回复
热议问题