How to make a deep copy of a List of Object

Hi I have a list of objects(list1) and I'd like to make a copy of this list but I want that the objects in the second list(list2) to not be linked to the one in first list.

this is what I do

    list<Obj> list1 = new list<Obj>{};
    // I fill the list1 with objects Obj
    // now I want to make a deep copy this is what I do

   list<Obj>  list2 = new list<Obj>(list1);
   // but when I edit an object in list 1 I also edit the object in list2

I'd like to be able to edit the objects in list1 without edititng the object in list2,how can I get that???

thanks for your answers

Upvotes: 0

Views: 7527

Answers (2)

onestarblack
onestarblack

Reputation: 814

You could add a copy constructor to your Obj.

Then loop through list1 create a new instance of your objects using the copy constructor and add it to list2.

Example:

Copy constructor:

public Obj(Obj copyFrom)
{
   this.field1 = copyFrom.field1;
   .
   .
}

With the following LINQ query you have a one liner to use the above contructor:

list2.AddRange(list1.Select(s => new Obj(s)));

Upvotes: 1

Patrick Hofman
Patrick Hofman

Reputation: 156928

You should implement the ICloneable interface in your Obj class. After that, you can call this code to create your second list:

list<Obj>  list2 = new list<Obj>(list1.Select(x => x?.Clone()));

It will clone every item in the list. (With null-check)

Upvotes: 2

Related Questions