How to clone a generic list in C#?

CsharpProgrammingServer Side Programming

A list is a Generic collection to hold elements of same datatypes.

To clone a list, you can use the CopyTo method.

Declare a list and add elements −

List < string > myList = new List < string > ();
myList.Add("Programming");
myList.Add("Web Dev");
myList.Add("Database");

Now create a new array and clone the list into it −

string[] arr = new string[10];
myList.CopyTo(arr);

Here is the complete code −

Example

 Live Demo

using System;
using System.Collections.Generic;
public class Demo {
   public static void Main() {

      List < string > myList = new List < string > ();
      myList.Add("Programming");
      myList.Add("Web Dev");
      myList.Add("Database");
      Console.WriteLine("First list...");

      foreach(string value in myList) {
         Console.WriteLine(value);
      }
      string[] arr = new string[10];
      myList.CopyTo(arr);
      Console.WriteLine("After cloning...");

      foreach(string value in arr) {
         Console.WriteLine(value);
      }
   }
}

Output

First list...
Programming
Web Dev
Database
After cloning...
Programming
Web Dev
Database
raja
Published on 21-Aug-2018 14:11:30
Advertisements