For example
List<string> name_list1 = new List<string>(); List<string> name_list2 = new List<string>();
later in the code:
name_list1.Add("McDonald"); name_list1.Add("Harveys"); name_list1.Add("Wendys"); name_list2 = name_list1; // I make a copy of namelist1 to namelist2
So, from this point I would like to keep adding element or making changes in name_list2 without affecting name_list1. How do I do that?
To add the contents of one list to another list which already exists, you can use: targetList. AddRange(sourceList); If you're just wanting to create a new copy of the list, see the top answer.
Lists are already passed by reference, in that all Python names are references, and list objects are mutable. Use slice assignment instead of normal assignment.
What you will need to do is iterate over one list, crate a new object, copy the property values over, and add it to the other list.
Another Options is : Deep Cloning
public static T DeepCopy<T>(T item) { BinaryFormatter formatter = new BinaryFormatter(); MemoryStream stream = new MemoryStream(); formatter.Serialize(stream, item); stream.Seek(0, SeekOrigin.Begin); T result = (T)formatter.Deserialize(stream); stream.Close(); return result; }
so,
you can use :
name_list2 = DeepCopy<List<string>>(name_list1);
OR:
name_list2 = DeepCopy(name_list1);
will also work.
name_list2 = new List<string>(name_list1);
This will clone the list.
Edit: This solution only works for primitive types. For objects, see other responses below.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With