Copy a List in C#

  1. Copy a List with Linq in C
  2. Copy a List with the List Constructor in C

This tutorial will introduce methods to create a separate copy of a list in C#.

Copy a List with Linq in C

The Linq can perform SQL-like queries on data structures in C#. We can use Linq with the pre-defined item.Clone() method to create a copy of a list. See the below example.

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

namespace copy_a_list
{
    static class Extensions
    {
        public static List<T> Clone<T>(this List<T> listToClone) where T : ICloneable
        {
            return listToClone.Select(item => (T)item.Clone()).ToList();
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            List<string> slist = new List<string> { "ABC", "DEF", "GHI" };
            List<string> tlist = slist.Clone();
            foreach (var t in tlist)
            {
                Console.WriteLine(t);
            }
        }
    }
}

Output:

ABC
DEF
GHI

We created the extension function Clone() to be used with a generic list. Clone() function uses item.Clone() function to make a separate copy of each element inside the list and then returns the result in the form of a list with the ToList() function in C#. In the main function, we initialized the list of strings slist and cloned it into another list of strings tlist. We can use this approach with both list of values and list of references.

Copy a List with the List Constructor in C

Another simpler method to create a copy of a list is to use the list constructor in C#. We can pass the previous list to the new list’s constructor to create a copy of the previous list. The following code example shows us how to create a separate copy of a list with the list constructor in C#.

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

namespace copy_a_list
{
    class Program
    {
        static void method2()
        {
        }
        static void Main(string[] args)
        {
            List<string> slist = new List<string> { "ABC", "DEF", "GHI" };
            List<string> tlist = new List<string>(slist);
            foreach (var t in tlist)
            {
                Console.WriteLine(t);
            }
        }
    }
}

Output:

ABC
DEF
GHI

This code is much simpler and more easy-to-understand than the previous approach. In the above code, we created a separate copy of the list slist into the tlist by passing slist as the argument of the constructor of tlist. We can only use this approach with the list of values.

Contribute
DelftStack is a collective effort contributed by software geeks like you. If you like the article and would like to contribute to DelftStack by writing paid articles, you can check the write for us page.

Related Article - Csharp List

  • Add List to Another List in C#
  • Declare a Multidimensional List in C#