snippetcsharpCritical
How do I clone a generic list in C#?
Viewed 0 times
listgenericclonehow
Problem
I have a generic list of objects in C#, and wish to clone the list. The items within the list are cloneable, but there doesn't seem to be an option to do
Is there an easy way around this?
list.Clone().Is there an easy way around this?
Solution
You can use an extension method.
static class Extensions
{
public static IList Clone(this IList listToClone) where T: ICloneable
{
return listToClone.Select(item => (T)item.Clone()).ToList();
}
}Code Snippets
static class Extensions
{
public static IList<T> Clone<T>(this IList<T> listToClone) where T: ICloneable
{
return listToClone.Select(item => (T)item.Clone()).ToList();
}
}Context
Stack Overflow Q#222598, score: 465
Revisions (0)
No revisions yet.