The following code snippet copies elements of a List collection to another List using C#. The code sample also shows how to insert a collection at a specified positon and remove a collection from a position and number of items in the collection. In the end, the code sample shows how to copy a List into a new List. The code is written using C# 10 and in Visual Studio 2022.
List.AddRange() method imports all elements of a collection to a List at the end of the collection.
// Program: Copy items from one list to another list
Console.WriteLine("Import one list to another!");
// Create List1
List<string> listOne = new();
listOne.Add("One");
listOne.Add("Two");
listOne.Add("Three");
listOne.Add("Four");
listOne.Add("Five");
// Create List2
List<string> listTwo = new();
listTwo.Add("A");
listTwo.Add("B");
listTwo.Add("C");
// Import all items of List2 to List1.
// AddRange adds the items of a collection to the end of the List<T>
listOne.AddRange(listTwo);
// Display
foreach (string item in listOne)
Console.WriteLine(item);
Console.WriteLine("------------------");
// Insert a collection at a specified positon
// InsertRange(index, collection) inserts a collection at the specified position
string[] insertItems = { "1", "2", "3", "4" };
listOne.InsertRange(2, insertItems);
foreach (string item in listOne)
Console.WriteLine(item);
// Remove a collection from a List<T>
// RemoveRange(index, count)
listOne.RemoveRange(2, 4);
Console.WriteLine("------------------");
// Copy a list to a new list
List<string> listThree = listOne.ToList();
// Display copied list
foreach (string item in listThree)
Console.WriteLine(item);
Console.ReadKey();