How to Change My New List Without Changing the Original List

How do I change my new list without changing the original list?

You need to clone your list in your method, because List<T> is a class, so it's reference-type and is passed by reference.

For example:

List<Item> SomeOperationFunction(List<Item> target)
{
List<Item> tmp = target.ToList();
tmp.RemoveAt(3);
return tmp;
}

Or

List<Item> SomeOperationFunction(List<Item> target)
{
List<Item> tmp = new List<Item>(target);
tmp.RemoveAt(3);
return tmp;
}

or

List<Item> SomeOperationFunction(List<Item> target)
{
List<Item> tmp = new List<Item>();
tmp.AddRange(target);
tmp.RemoveAt(3);
return tmp;
}

How can I append items to a list without changing the original list

Variables in Python are just references. I recommend making a copy by using a slice. l_copy = l_orig[:]

When I first saw the question (pre-edit), I didn't see any code, so I did not have the context. It looks like you're copying the reference to that row. (Meaning it actually points to the sub-lists in the original.)

new_list.append(row[:])

Change the copy of the list without changing the orginal one in Lisp

Copy the list with COPY-LIST. The you can delete or add elements of the new list and the old list won't change.

Changes made in Python list showing up in copy of original list

Use copy.deepcopy:

from copy import deepcopy

desc1 = deepcopy(desc)

list.copy only makes a shallow copy: a new list object, but its elements (here mutable sublists) will be references to the same objects as the elements of the original.

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

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 */
};
}
}


Related Topics



Leave a reply



Submit