cloning a list in C#

23,238

Solution 1

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();

Solution 2

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.

Share:
23,238
Nadav
Author by

Nadav

Updated on July 09, 2022

Comments

  • Nadav
    Nadav almost 2 years

    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.