简体   繁体   中英

How to deep copy a matrix in C#?

I got a 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 has to be copied into the new matrix.

How would you do that in an efficient way?

For a CustomClass that implements ICloneable, this isn't very difficult:

var myList = new List<List<CustomClass>>();

//populate myList

var clonedList = new List<List<CustomClass>>();

//here's 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 make this work in a similar way with any "DeepCopy"-type method, if you feel you don't want to implement ICloneable (I would recommend using the built-in interface though).

One easier way to serialize the whole object and then deserialize it 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);
  }
}

USAGE

List<List<CustomClass>> foobar = GetListOfListOfCustomClass();

List<List<CustomClass>> deepClonedObject = foobar.DeepClone();

There are two possibilities:

  1. Implement the ICloneable interface on your CustomClass, then you can clone your objects.

  2. If the class can be serialized, serialize it to a memory stream and deserialize it from there. That will create a copy of it.

I would prefer to take the first alternative, because I think serializing / deserializing is slower than cloning via ICloneable.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM