We can easily clone or copy a list to another list or array in C#. In this blog, we will use 3 different methods to clone or copy a list. It is very simple to do if you see our examples.
- Using List Constructor
- Using Enumerable.ToList Method (System.Linq)
- Using List<T>.CopyTo Method
Using List Constructor
First, we use the List constructor to inject/pass the source list, this will create a copy of the list which you passed through the constructor. The below code snippet shows how to clone the list using the List constructor.
class CloneList
{
static void Main(string[] args)
{
// Original List
var sourceList = new List<string>() { "Ford", "BMW", "Audi", "Toyota" };
// Copied/Cloned List
var clonedList = new List<string>(sourceList);
// Print Cloned List
Console.WriteLine(String.Join(",", clonedList));
Console.ReadKey();
}
}
Output:
Ford,BMW,Audi,Toyota
Using Enumerable.ToList Method (System.Linq)
We use ToList()
method to copy or clone the list to another list as shown in the below example. The ToList()
returns the new List<T>
that containing the original list.
class CloneList
{
static void Main(string[] args)
{
// Original List
var sourceList = new List<string>() { "Ford", "BMW", "Audi", "Toyota" };
// Copied/Cloned List
List<string> clonedList = sourceList.ToList();
// Print Cloned List
Console.WriteLine(String.Join(",", clonedList));
Console.ReadKey();
}
}
Output:
Ford,BMW,Audi,Toyota
Using List<T>.CopyTo Method
In this method, we use CopyTo()
method to copy the entire List<T> to a one-dimensional array, starting at the beginning of the target array. as shown below.
class CloneList
{
static void Main(string[] args)
{
// Original List
var sourceList = new List<string>() { "Ford", "BMW", "Audi", "Toyota" };
string[] arr = new string[10];
// Copied/Cloned List to Array
sourceList.CopyTo(arr);
// Print Cloned List
foreach (string value in arr)
{
Console.WriteLine(value);
}
Console.ReadKey();
}
}
Output:
Ford
BMW
Audi
Toyota
Comments (0)