c sharp

How to Copy List in C#

In software development, working with lists is a common task, and sometimes you may need to create a copy of a list for various purposes. Copying a list in PHP allows you to modify the copied version without affecting the original list. It is an essential technique to ensure data integrity and maintain the original state of your data.

In this detailed guide, we will use different methods to effectively copy lists in C#.

Copy List in C#

There are two approaches to copying a list in C#:

1: Shallow Copy

In C# when we make a shallow copy of a list, it means creating a new list that points to the same objects as the original list. So, if we change something in the original list, the copied list will show those changes too.

To perform a shallow copy in C#, we have different methods available:

  • clone() Method
  • List Copy Constructor
  • ToList() Method

i: Using the item.clone() Method

The item.Clone() method is used to create a separate copy of each element in the list. It ensures that both the values and references of the elements are copied correctly. This way, any editions or changes made to the original list will not affect the copied list.

After creating separate copies of each element using the item.Clone(), the resulting copied elements are then returned to the ToList() function. The ToList() function is responsible for converting the copied elements into a new list.

For example:

using System;
using System.Collections.Generic;
using System.Linq;

public static class Extensions
{
    public static List GetClone(this List source)
    {
        return source.Select(item => (string)item.Clone()).ToList();
    }
}
public class Example
{
    public static void Main()
    {
        List source = new List() { "Ford", "BMW", "Audi" };
        List clonedList = source.GetClone();
        Console.WriteLine("Original List: " + String.Join(",", source));
        Console.WriteLine("Cloned List: " + String.Join(",", clonedList));
    }
}

The above code defines an extension method GetClone() for the List<string> class. This method creates a separate copy of each element in the source list using the Clone() method and returns a new list containing the copied elements.

In the Example class, the code demonstrates the usage of the GetClone() method. It creates a source list with three elements. By calling GetClone(), a new list clonedList is created with the copied elements from the source list. The code then displays the original list and the cloned list using the Console.WriteLine() function.

ii: Using List Copy Constructor

In C#, there is no specific copy constructor available to clone a list. However, we can create a clone of a list by initializing a new List<T> object with the elements of the original list. This process performs a shallow copy, meaning the new list will have a reference of objects of the original list.

using System;
using System.Collections.Generic;
public class Example
{
    public static void Main()
    {
        List source = new List() { "London", "Paris", "New York" };
        List clonedList = new List(source);
        Console.WriteLine("Original List:");
        Console.WriteLine(String.Join(",", source));
        Console.WriteLine("Cloned List:");
        Console.WriteLine(String.Join(",", clonedList));
    }
}

In the above code, a new list called source is created and initialized with three string elements. Then, a new list called clonedList is created by passing the source list as an argument to the copy constructor.

Finally, the original list and the cloned list are printed separately to the console, showing their respective elements.

iii: Using Enumerable.ToList() Method

Another way to create the shallow copy of the list in C# is to call the method ToList() in the original list. The following example code explains the usage of this method, which is used under the header system.Linq:

using System;
using System.Linq;
using System.Collections.Generic;
 
public class Example
{
    public static void Main()
    {
        List source = new List() { "UK", "USA", "Turkey" };
        List clonedList = source.ToList();
        Console.WriteLine("Original List:");
        Console.WriteLine(String.Join(",", source));
        Console.WriteLine("Cloned List:");
        Console.WriteLine(String.Join(",", clonedList));
    }
}

In the code, a new list called source is initialized with three string elements. Then, the ToList() method is used on the source list to create a new list called clonedList, which is a shallow copy of the original list.

Finally, the original list and the cloned list are printed separately to the console, showing their respective elements.

2: Deep Cloning

The deep cloning copies each element of the original list and creates a new list. If you made the changes in one list, it will not affect the copied list. To perform deep cloning, iterate over the elements of the original list. The following method deep clones the list in C#:

  • List<T>.GetRange()
  • Serialization and Deserialization

i: Using List<T>.GetRange()

You can copy the elements of one list to the Tolist() using this method. It enables users to copy the elements within the specified range.

For example:

using System;
using System.Collections.Generic;

public static class Extension
{
    public static List GetClone(this List source)
    {
        return source.GetRange(0, source.Count);
    }
}
public class Example
{
    public static void Main()
    {
        List source = new List() { "C#", "PHP", "C" };
        List clonedList = source.GetClone();
        Console.WriteLine("Original List:");
        Console.WriteLine(String.Join(",", source));
        Console.WriteLine("Cloned List:");
        Console.WriteLine(String.Join(",", clonedList));
    }
}

The given code provides a way to create a clone of a list in C#. It defines an extension method GetClone<T>() within the Extensions class, which can be used to clone a generic list. In the Main() method, a sample list of strings is created and then cloned using the GetClone() method. The original list and cloned list are then printed separately to verify the cloning process.

ii: Using Serialization and Deserialization

Another method to perform a deep clone of a list in C# is serialization and deserialization. This process involves serializing the original list to a stream and then using deserializing back into a new list.

For example:

using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;

public class Example
{
    public static void Main()
    {
        List source = new List() { "Zainab", "Awais", "Sam" };
        List clonedList = DeepClone(source);
        Console.WriteLine("Original List:");
        Console.WriteLine(String.Join(",", source));
        Console.WriteLine("Cloned List:");
        Console.WriteLine(String.Join(",", clonedList));
    }
    public static List DeepClone(List source)
    {
        BinaryFormatter formatter = new BinaryFormatter();
        MemoryStream stream = new MemoryStream();
        formatter.Serialize(stream, source);
        stream.Position = 0;
        List clonedList = (List)formatter.Deserialize(stream);
        stream.Close();
        return clonedList;
    }
}

In this example, the DeepClone method uses the BinaryFormatter class to serialize the original list source to a memory stream, and then deserialize it back into a new list clonedList. This process creates an identical copy of each object in the list, resulting in a deep clone.

Bottom Line

Copying lists in C# involves shallow copy and deep copy methods. Shallow copy shares object references, while deep copy creates separate copies. Shallow copy methods include item.Clone(), copy constructor, and Enumerable.ToList(). Deep copy methods include List<T>.GetRange() and serialization/deserialization. You must choose the appropriate method based on your needs for data integrity and object independence.

About the author

Zainab Rehman

I'm an author by profession. My interest in the internet world motivates me to write for Linux Hint and I'm here to share my knowledge with others.