1

Possible Duplicate:
How do I clone a generic list in C#?

hey i have been trying to clone a list and so far i found the function addRange but i am pretty sure it does not clone the objects inside the list but doing a shallow copy of the list i would like to know how to clone the list thanks in advance.

Community
  • 1
  • 1
Nadav
  • 2,589
  • 9
  • 44
  • 63

3 Answers3

9

To clone a list, each individual item has to be cloned. Provided a useful implementation of Clone() for the item class exists, this is a one-liner using LINQ:

List<MyType> lstCloned = lstOriginal.Select(i => i.Clone()).ToList();
TeaDrivenDev
  • 6,591
  • 33
  • 50
4

AddRange, and more generally all operations on objects contained in list only clones references to these objects. To clone objects themselves, you should handle the copy at the object level itself.

What do you mean by "clone the list" ? Clone the objects ? You can implement it explicitly on each objects (by realizing ICloneable interface for example), or make a general implementation using Reflection.

Look for "ICloneable", "deep cloning" or "deep copy" to learn more on the different ways to get the expected result.

AFract
  • 8,868
  • 6
  • 48
  • 70
0

You will need to parse the list and create a new object for each item then the new item add it to a new list.

Liviu Mandras
  • 6,540
  • 2
  • 41
  • 65