0

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

  • 1
    Look at the [ICloneable interface](https://msdn.microsoft.com/en-us/library/system.icloneable(v=vs.110).aspx) – Steve Feb 01 '16 at 11:52
  • Assuming your Obj isn't a value type you will have to loop through your 'list1' and clone each individual object (and add that to list2). – Mark Feb 01 '16 at 11:53
  • 1
    If you don't want to implement ICloneable, you can use this method: http://stackoverflow.com/a/78612/891715 – Arie Feb 01 '16 at 12:06

2 Answers2

2

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)

Patrick Hofman
  • 153,850
  • 22
  • 249
  • 325
1

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)));
onestarblack
  • 774
  • 7
  • 21