I have a generic list of objects in C#, and wish to clone the list. The items within the list are cloneable, but there doesn't seem to be an option to do list.Clone()
.
Is there an easy way around this?
I have a generic list of objects in C#, and wish to clone the list. The items within the list are cloneable, but there doesn't seem to be an option to do list.Clone()
.
Is there an easy way around this?
There is a simple way to clone objects in C# using a JSON serializer and deserializer.
You can create an extension class:
To clone and object:
The following code should transfer onto a list with minimal changes.
Basically it works by inserting a new random number from a greater range with each successive loop. If there exist numbers already that are the same or higher than it, shift those random numbers up one so they transfer into the new larger range of random indexes.
You could also simply convert the list to an array using
ToArray
, and then clone the array usingArray.Clone(...)
. Depending on your needs, the methods included in the Array class could meet your needs.