Wednesday, October 7, 2009

How to create a deep copy of List<> object in C#

Following Utility method will create a deep copy of list.

public static List CloneList(List oldList)

{

BinaryFormatter formatter = new BinaryFormatter();
MemoryStream stream = new MemoryStream();
formatter.Serialize(stream, oldList);
stream.Position = 0;
return (List)formatter.Deserialize(stream);
}

Use:

List allOrders = Utility.CloneList(OldList);

No comments: