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:
xxxxxxxxxx
1
List<int> myList = new List<int> { 1, 2, 3 };
2
3
List<int> copy = new List<int>(myList);
or:
xxxxxxxxxx
1
List<int> myList = new List<int> { 1, 2, 3 };
2
3
List<int> copy = myList.ToList();
or:
xxxxxxxxxx
1
List<int> myList = new List<int> { 1, 2, 3 };
2
3
List<int> copy = myList.GetRange(0, myList.Count);
In this example, we create copy of myList
using List Constructor.
xxxxxxxxxx
1
using System;
2
using System.Collections.Generic;
3
4
public class Program
5
{
6
public static void Main()
7
{
8
List<int> myList = new List<int> { 1, 2, 3 };
9
10
List<int> copy = new List<int>(myList);
11
12
foreach (int item in copy)
13
Console.WriteLine(item);
14
}
15
}
Output:
xxxxxxxxxx
1
1
2
2
3
3
In this example, we use ToList()
method from System.Linq
to create a copy of myList
.
xxxxxxxxxx
1
using System;
2
using System.Linq;
3
using System.Collections.Generic;
4
5
public class Program
6
{
7
public static void Main()
8
{
9
List<int> myList = new List<int> { 1, 2, 3 };
10
11
List<int> copy = myList.ToList();
12
13
foreach (int item in copy)
14
Console.WriteLine(item);
15
}
16
}
Output:
xxxxxxxxxx
1
1
2
2
3
3
In this example, we use getRange()
to copy elements from myList
into a new List.
xxxxxxxxxx
1
using System;
2
using System.Collections.Generic;
3
4
public class Program
5
{
6
public static void Main()
7
{
8
List<int> myList = new List<int> { 1, 2, 3 };
9
10
List<int> copy = myList.GetRange(0, myList.Count);
11
12
foreach (int item in copy)
13
Console.WriteLine(item);
14
}
15
}
Output:
xxxxxxxxxx
1
1
2
2
3
3
Note:
All of the presented solutions present how to create a shallow copy of the List.