Clone a generic list in C# using extension method

In practical situation you need to clone of object so that change in cloned object will not affect the original one.
If you need a cloned list with the same capacity you need to do some extra stuff with your user type.

I came up with this easy solution using ICloneable interface in your custom type class.

The first step you need to implement the ICloneable interface in your class like below.


 public class MyClassDto : ICloneable  
   {  
     public Int64 Id { get; set; }  
     public string Time { get; set; }  
     public int user{ get; set; }  
     public object Clone()  
     {  
       return new MyClassDto{ Date = this.Date, Id = this.Id, user = this.user};  
     }  
   }  

after that you need to add extension method in common class so that you can use it everywhere you want.

 public static class Extensions  
   {  
     public static List<T> Clone<T>(this List<T> listToClone) where T : ICloneable  
     {  
       return listToClone.Select(item => (T)item.Clone()).ToList();  
     }  
   }  

the above extension will clone the list and return the cloned list using linq.


you can now use the extension in your code where you want to cloned generic list.



 List<MyClassDto> lst=new List<MyClassDto>();  
 lst.Add(new MyClassDto{id=1,Time="10.20",user=2})  
 lst.Add(new MyClassDto{id=2,Time="10.21",user=3})  
 var userInfoPush = lst.Clone<MyClassDto>(); 




That's it. Now your generic list will be cloned successfully

Comments

Popular posts from this blog

Implement Logging in CSV file using Nlog in .net core MVC application- part 2

Implement Nlog in .Net core MVC application part 1

Angular User Session Timeout example step by step

Restore the lost focus of Auto post back controls in asp.net update Panel control

Disable backspace key using Jquery