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?
For a shallow copy, you can instead use the GetRange method of the generic List class.
Quoted from: Generics Recipes
My friend Gregor Martinovic and I came up with this easy solution using a JavaScript Serializer. There is no need to flag classes as Serializable and in our tests using the Newtonsoft JsonSerializer even faster than using BinaryFormatter. With extension methods usable on every object.
Standard .NET JavascriptSerializer option:
Faster option using Newtonsoft JSON:
Another thing: you could use reflection. If you'll cache this properly, then it'll clone 1,000,000 objects in 5.6 seconds (sadly, 16.4 seconds with inner objects).
I measured it in a simple way, by using the Watcher class.
RESULT: With inner object PersonInstance - 16.4, PersonInstance = null - 5.6
CopyFactory is just my test class where I have dozen of tests including usage of expression. You could implement this in another form in an extension or whatever. Don't forget about caching.
I didn't test serializing yet, but I doubt in an improvement with a million classes. I'll try something fast protobuf/newton.
P.S.: for the sake of reading simplicity, I only used auto-property here. I could update with FieldInfo, or you should easily implement this by your own.
I recently tested the Protocol Buffers serializer with the DeepClone function out of the box. It wins with 4.2 seconds on a million simple objects, but when it comes to inner objects, it wins with the result 7.4 seconds.
SUMMARY: If you don't have access to the classes, then this will help. Otherwise it depends on the count of the objects. I think you could use reflection up to 10,000 objects (maybe a bit less), but for more than this the Protocol Buffers serializer will perform better.
If you need a cloned list with the same capacity, you can try this:
Unless you need an actual clone of every single object inside your
List<T>
, the best way to clone a list is to create a new list with the old list as the collection parameter.Changes to
myList
such as insert or remove will not affectcloneOfMyList
and vice versa.The actual objects the two Lists contain are still the same however.
You can use extension method:
You can clone all objects by using their value type members for example, consider this class:
Note: if you do any change on copy (or clone) it will not affect the original object.