Techiehook Techiehook
Updated date Mar 24, 2024
Explore efficient ways to clone lists in C# with practical code examples. Learn how to create a copy of a list using the List T constructor and LINQs ToList() method, ensuring a clear understanding of the process.

Clone or Copy a List in C#

Cloning a list in C# is a common 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. By passing 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!!!