Translate

Wednesday, August 14, 2013

c# Deep Copy List


In the example below I will take a List of Dog and copy it into another List of Dog. To do that, I will use DataContractSerializer to serialize the original object into an XML and the deserialize it from the XML back into an object.

To follow the example, add a reference to the System.Runtime.Serialization dll as shown in the image on the right.



using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization;
 
namespace ConsoleApplication29
{
    class Program
    {
 
        static void Main(string[] args)
        {
            var dogs = new List<Dog> {new Dog {Age = 2, IsBig = true}, new Dog {Age = 3, IsBig = false}};
 
            List<Dog> dogsCopy;
 
            var ds = new DataContractSerializer(typeof(List<Dog>));
 
            using (var s = File.Create("Dog.xml"))
            {
                ds.WriteObject(s, dogs);//Serialize into an xml file
            }
 
            using (var s = File.OpenRead("Dog.xml"))
            {
                dogsCopy = (List<Dog>)ds.ReadObject(s);//Deserialize from an xml file and cast into an object
            }
        }
 
    }
 
    public class Dog  
    {
        public int Age { getset; }
        public bool IsBig { getset; }
 
    }
}

No comments:

Post a Comment

Comments will appear once they have been approved by the moderator