Kenneth Bo Christensen Kenneth Bo Christensen - 3 months ago 9
C# Question

Make an independent duplication of a List<T>

I make two List< Test> called listA and listB.
I save a peace of data in listA.
I copy the data from listA to listB.
I change the data in listB.
When I change the data in listB it also changes in listA – is it posible to avoid this?

I hope you can help me out there :o)

public class Test
{
public string Name { get; set; }
}

static void Test()
{
List<Test> listA = new List<Test>();
List<Test> listB = new List<Test>();

listA.Add(new Test { Name = "A" });
listB.AddRange(listA);

//I change the data in listB and the data in listA also get changed.
listB.First().Name = "B";
Console.WriteLine("listA: {0} listB: {1}", listA.First().Name, listB.First().Name);

//Can I avoid the change of data in listA?
}

Answer

You will have to create new instances of the Test object.

You could add a copy method to your test class to make it a bit easier to copy the members using MemberwiseClone, this will be good if you have losts of properties to copy without needing big select statments to populate each property.

public class Test
{
    public string Name { get; set; }

    public Test Copy()
    {
        return (Test)this.MemberwiseClone();
    }
}

Then you can use where needed in your code.

  List<Test> listA = new List<Test>();
  List<Test> listB = new List<Test>();
  listA.Add(new Test { Name = "A" });

  listB.AddRange(listA.Select(x => x.Copy()));