Languages
[Edit]
EN

C# / .NET - copy List<> to another list

0 points
Created by:
martineau
1380

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.

References

  1. List<T>.GetRange(Int32, Int32) Method (System.Collections.Generic) | Microsoft Docs
  2. Enumerable.ToList<TSource>(IEnumerable<TSource>) Method (System.Linq) | Microsoft Docs

Alternative titles

  1. C# / .NET - clone List<> to another list
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join