Wednesday, October 17, 2012

Clone Generic List in C# using an Extension method

Explore the Top Microsoft SQLServer Technical/ Interview Questions here: http://XploreSqlServer.blogspot.com/
   
Explore the Top Microsoft C# Technical/ Interview Questions here: http://XploreCSharpDotNet.blogspot.com

Explore the Top Microsoft Blazor Technical/ Interview Questions here: https://XploreBlazor.blogspot.com/

See below the plain readable code for cloning a generic collection in C#:

namespace Org.Project.Common
{
  using System;
  using System.Collections.Generic;
   public static class CloneableExtension
   {
     public static IList<T> Clone<T>(this IList<T> list) where T : ICloneable
     {
        IList<T> clonedList;
        clonedList = new List<T>();
        foreach (T cloneable in list)
        {
          object clonedObj = cloneable.Clone();
          clonedList.Add((T)clonedObj);
        }
        return clonedList;

     }
  }
  
}

The method extends all collections that implements IList but returns instance of List always.
The objects of type T that the list consists of should implement ICloneable interface.

Here is another stylish implementation using LINQ:

namespace Org.Project.Common{
  using System;
  using System.Collections.Generic;
  using System.Linq;
  public static class CloneableExtension
  {
   public static IList<T> Clone<T>(this IList<T> list) where T : ICloneable
   {     return list.Select(item => (T)item.Clone()).ToList();    }
  }
}


Explore the Top Microsoft SQLServer Technical/ Interview Questions here: http://XploreSqlServer.blogspot.com/
   
Explore the Top Microsoft C# Technical/ Interview Questions here: http://XploreCSharpDotNet.blogspot.com

6 comments:

  1. I found your blog while searching for the updates, I am happy to be here. Very useful content and also easily understandable providing.. Believe me I did wrote an post about tutorials for beginners with reference of your blog. 
    rpa training in bangalore
    best rpa training in bangalore
    RPA training in bangalore
    rpa course in bangalore
    rpa training in chennai
    rpa online training

    ReplyDelete
  2. Really great post, I simply unearthed your site and needed to say that I have truly appreciated perusing your blog entries. I want to say thanks for great sharing.
    Selenium training in Chennai
    Selenium training in Bangalore
    Selenium training in Pune
    Selenium Online training

    ReplyDelete
  3. This is a nice post in an interesting line of content.Thanks for sharing this article, great way of bring this topic to discussion.
    AWS Training in pune
    AWS Online Training

    ReplyDelete