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?
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?
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.
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.