Copy generic list without references

28/07/2016 10:04

Sometimes we need to make new generic list based on another list - by query or other. But when we change list2 properties, list1 is also changed. That's why we need to make list1 copy without references.


Here is the code to create the copy


Add following code to ListExtensions.cs file

 public static class ListExtensions
 {
 public static List<T> DeepCopy<T>(this IList<T> list)
 {
  var retval = new List<T>();
  foreach (var item in list)
  {


   BinaryFormatter formatter = new BinaryFormatter();
   MemoryStream stream = new MemoryStream();
   formatter.Serialize(stream, item);
   stream.Seek(0, SeekOrigin.Begin);
   T result = (T)formatter.Deserialize(stream);
   stream.Close();

   retval.Add(result);
  }
  return retval;
 }
}

Call function as following


list1.DeepCopy();

Note: sometimes T class must be marked as Serializable using [Serializable] flag on the top of class declaration