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


Popular posts from this blog

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

Disable backspace key using Jquery

Step by step migration of ASP.NET Core 2.2 to 3.1

Add Comma automatically while entering amounts in textbox using Javascript

Remove Owin from MVC 5 Application and use custom forms authentication

Source Code Beautifier And Format Source Code For Blogger and Websites

Email validation using regular expression in jQuery

Send bulk Email in using excel file