Techiehook Techiehook
Updated date Jul 02, 2024
We will explore easy ways to clone lists in C# with examples. Also, learn how to create a copy of a list using the List T constructor and LINQs ToList() method.
  • 9.3k
  • 0
  • 0

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

ABOUT THE AUTHOR

Techiehook
Techiehook
Admin, Australia

Welcome to TechieHook.com! We are all about tech, lifestyle, and more. As the site admin, I share articles on programming, tech trends, daily life, and reviews... For more detailed information, please check out the user profile

https://www.techiehook.com/profile/alagu-mano-sabari-m

Comments (0)

There are no comments. Be the first to comment!!!