Clone or Copy a List in C#
Cloning a list in C# is a simple operation when you need to create a copy of an existing list without modifying the original. In this article, we will explore various methods to clone a list in C# and provide example programs along with their outputs.
Method 1: Using the List<T> Constructor
The List<T> class in C# has a constructor that takes another IEnumerable<T> as a parameter. Bypassing the original list to this constructor, we can create a new list with the same elements.
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
// Original list
List<int> originalList = new List<int> { 1, 2, 3, 4, 5 };
// Cloning using List<T> constructor
List<int> clonedList = new List<int>(originalList);
// Output
Console.WriteLine("Original List: " + string.Join(", ", originalList));
Console.WriteLine("Cloned List: " + string.Join(", ", clonedList));
}
}
Output:
Original List: 1, 2, 3, 4, 5
Cloned List: 1, 2, 3, 4, 5
Method 2: Using LINQ's ToList() Method
LINQ provides the ToList()
extension method, which can be used to create a shallow copy of a list.
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main()
{
// Original list
List<int> originalList = new List<int> { 1, 2, 3, 4, 5 };
// Cloning using LINQ's ToList() method
List<int> clonedList = originalList.ToList();
// Output
Console.WriteLine("Original List: " + string.Join(", ", originalList));
Console.WriteLine("Cloned List: " + string.Join(", ", clonedList));
}
}
Output:
Original List: 1, 2, 3, 4, 5
Cloned List: 1, 2, 3, 4, 5
Comments (0)