How to copy List in C#
Asked Answered
I

1

8

I want to copy a List of Objects, but i keep getting references between the objects.

List<MyClass> copy = original;

When i change the value in the copy List, the original List ends up modified also. Is there a way to work around it?

Inveigh answered 11/3, 2013 at 3:25 Comment(1)
check this post: https://mcmap.net/q/497895/-cloning-list-lt-t-gtHomely
S
14

You can do this:

List<MyClass> copy = original.ToList();

This would make an element-by-element copy of the list, rather than copying the reference to the list itself.

Sidewinder answered 11/3, 2013 at 3:26 Comment(5)
@Inveigh Could you please be more specific about the "not working" part?Sidewinder
when i changed the value of the copy list, the original list is getting modified tooInveigh
@Inveigh Right - that's because the copy is shallow. If you add or remove items to/from the original, the copy is not going to "see" that change. However, changing mutable objects inside the list would be reflected in the copy as well.Sidewinder
would deep copy maintain the value in the original list even if the copy list is modified?Inveigh
@Inveigh Yes. If you want a deep copy, use List<MyClass> copy = original.Select(v => new MyClass(v)).ToList(); (assuming that MyClass has a "copy constructor" that takes an instance of the same class and returns a "deep copy" of the object).Sidewinder

© 2022 - 2024 — McMap. All rights reserved.