How to deep copy a matrix in C #?

I got List<List<CustomClass>> where CustomClass is a reference type.

I need to make a full deep copy of this matrix into a new one. Since I want a deep copy, each CustomClass object in the matrix needs to be copied to the new matrix.

How would you do this in an effective way?

+4
source share
4 answers

For a CustomClass that implements ICloneable, this is not very difficult:

 var myList = new List<List<CustomClass>>(); //populate myList var clonedList = new List<List<CustomClass>>(); //here the beef foreach(var sublist in myList) { var newSubList = new List<CustomClass>(); clonedList.Add(newSubList); foreach(var item in sublist) newSublist.Add((CustomClass)(item.Clone())); } 

You can do this work in the same way with any method like "DeepCopy" if you think you don't want to implement ICloneable (I would recommend using the built-in interface, though).

+4
source

Another way to serialize the entire object and then deserialize again, try this extension method:

 public static T DeepClone<T>(this T source) { if (!typeof(T).IsSerializable) { throw new ArgumentException("The type must be serializable.", "source"); } // Don't serialize a null object, simply return the default for that object if (Object.ReferenceEquals(source, null)) { return default(T); } IFormatter formatter = new BinaryFormatter(); Stream stream = new MemoryStream(); using (stream) { formatter.Serialize(stream, source); stream.Seek(0, SeekOrigin.Begin); return (T)formatter.Deserialize(stream); } } 

USING

 List<List<CustomClass>> foobar = GetListOfListOfCustomClass(); List<List<CustomClass>> deepClonedObject = foobar.DeepClone(); 
+3
source

There are two possibilities:

  • Embed the ICloneable interface in your CustomClass, then you can clone your objects.

  • If the class can be serialized, serialize it into a memory stream and deserialize it from there. This will create a copy of it.

I would rather use the first alternative because I think serialization / deserialization is slower than cloning via ICloneable.

+1
source

Assuming you have a Copy method that can duplicate CustomClass objects:

 var newMatrix = oldMatrix .Select(subList => subList.Select(custom => Copy(custom)).ToList()) .ToList(); 
+1
source

Source: https://habr.com/ru/post/1382517/


All Articles