0

I have a list that I want to copy to another list.

I have 'employeeAddressDataToSave' List and I want to copy this list to 'employeeAddressDataToSaveReturn' List.

I'm using the following code to do that. After I set this, further down the road, I'm updating employeeAddressDataToSave List. Those changes are automatically getting to 'employeeAddressDataToSaveReturn' list. I don't want my employeeAddressDataToSaveReturn list to be updated with changes to employeeAddressDataToSave . Is there a way to do that?

employeeAddressDataToSaveReturn = new List<Address>(employeeAddressDataToSave);
Scott Chamberlain
  • 124,994
  • 33
  • 282
  • 431
Ninja.J
  • 37
  • 1
  • 1
  • 1

2 Answers2

3

You are performing a shallow copy of the list, you need to perform a deep copy of it. The list are two separate lists, but the items in the list are shared between them. If you edit a item, not the list itself, the edit will show up in both.

You will need to provide some method to copy Address when making the new list.

employeeAddressDataToSaveReturn = new List<Address>(employeeAddressDataToSave.Select(x=>x.Copy());`

This now calls the Address.Copy() method (which you will need to write) and it will return a copy of itself.

Here is a quick example, you did not show Address so I will have to make one up

class Address
{
    public string Street {get;set;}
    public string Zip {get;set;}

    public Address Copy()
    {
        var result = new Address();
        result.Street = this.Street;
        retult.Zip = this.Zip;
        return result;
    }
}

If Address contains nested mutable classes you will need to write a Copy() method for them too and call Copy() recursively.

Community
  • 1
  • 1
Scott Chamberlain
  • 124,994
  • 33
  • 282
  • 431
2

Your lists don't contain address data items, they contain references to address data items. The lists are separate, meaning that if you add a reference to an address to list2, it is not added to list1:

var list1 = GetList1();
Console.WriteLine(list1.Count); // 3
var list2 = new List(list1);
list2.Add(new AddressData("John Doe", "Foo street", "12345"); 
Console.WriteLine(list1.Count); // 3
Console.WriteLine(list2.Count); // 4

However if you edit an item in list1, you will also modify it in the other list

Console.WriteLine(list1[2].Name); // Bob
Console.WriteLine(list2[2].Name); // Bob
list2[2].Name = "Jim";
Console.WriteLine(list1[2].Name); // Jim <-- Changed
Console.WriteLine(list2[2].Name); // Jim 

If you want to make a deep copy, implement a copy/clone method on your address class, and copy the whole list, item by item

list2 = list1.Select(a => a.Copy()).ToList();
Anders Forsgren
  • 10,827
  • 4
  • 40
  • 77