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/
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 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