EN
C# / .NET - copy List<> to another list
0
points
In this article, we would like to show you how to copy List to another List in C#.
Quick solution:
List<int> myList = new List<int> { 1, 2, 3 };
List<int> copy = new List<int>(myList);
or:
List<int> myList = new List<int> { 1, 2, 3 };
List<int> copy = myList.ToList();
or:
List<int> myList = new List<int> { 1, 2, 3 };
List<int> copy = myList.GetRange(0, myList.Count);
Practical example
In this example, we create copy of myList using List Constructor.
using System;
using System.Collections.Generic;
public class Program
{
public static void Main()
{
List<int> myList = new List<int> { 1, 2, 3 };
List<int> copy = new List<int>(myList);
foreach (int item in copy)
Console.WriteLine(item);
}
}
Output:
1
2
3
2. Using Linq ToList()
In this example, we use ToList() method from System.Linq to create a copy of myList.
using System;
using System.Linq;
using System.Collections.Generic;
public class Program
{
public static void Main()
{
List<int> myList = new List<int> { 1, 2, 3 };
List<int> copy = myList.ToList();
foreach (int item in copy)
Console.WriteLine(item);
}
}
Output:
1
2
3
3. Using getRange()
In this example, we use getRange() to copy elements from myList into a new List.
using System;
using System.Collections.Generic;
public class Program
{
public static void Main()
{
List<int> myList = new List<int> { 1, 2, 3 };
List<int> copy = myList.GetRange(0, myList.Count);
foreach (int item in copy)
Console.WriteLine(item);
}
}
Output:
1
2
3
Note:
All of the presented solutions present how to create a shallow copy of the List.