Clone a List in C#
This post will discuss how to clone a list in C#. The solution should construct a list containing the specified list elements in the same order as the original list.
1. Using List Constructor
To clone a list, we can use a copy constructor, which is a special constructor to initialize a new instance of the List<T>
class with a copy of the existing list. Assuming there are no mutable objects in the list, the copy constructor performs a shallow copy.
This method is demonstrated below:
using System; using System.Collections.Generic; public class Example { public static void Main() { List<string> source = new List<string>() { "A", "B", "C" }; List<string> clonedList = new List<string>(source); Console.WriteLine(String.Join(",", clonedList)); } } /* Output: A,B,C */
2. Using List<T>.GetRange()
(System.Collections.Generic
)
We can also use List<T>.GetRange() method that creates a shallow copy of the source List<T>
between the specified range.
using System; using System.Collections.Generic; public static class Extensions { public static List<T> GetClone<T>(this List<T> source) { return source.GetRange(0, source.Count); } } public class Example { public static void Main() { List<string> source = new List<string>() { "A", "B", "C" }; List<string> clonedList = source.GetClone(); Console.WriteLine(String.Join(",", clonedList)); } } /* Output: A,B,C */
3. Using Enumerable.ToList()
method (System.Linq
)
Another approach that creates shallow copy is to call the ToList() on the original list. The following code example demonstrates how ToList()
returns a new List<T>
containing elements of the original list in the same order.
using System; using System.Linq; using System.Collections.Generic; public class Example { public static void Main() { List<string> source = new List<string>() { "A", "B", "C" }; List<string> clonedList = source.ToList(); Console.WriteLine(String.Join(",", clonedList)); } } /* Output: A,B,C */
The following code demonstrates how to call the default Clone()
method on each list element. Then ToList()
method is called to force immediate query evaluation and return a List<T>
containing the query results.
using System; using System.Collections.Generic; using System.Linq; public static class Extensions { public static List<string> GetClone(this List<string> source) { return source.Select(item => (string)item.Clone()) .ToList(); } } public class Example { public static void Main() { List<string> source = new List<string>() { "A", "B", "C" }; List<string> clonedList = source.GetClone(); Console.WriteLine(String.Join(",", clonedList)); } } /* Output: A,B,C */
That’s all about cloning a List in C#.