C# program to clone or copy a list

CsharpProgrammingServer Side Programming

To copy or clone a C# list, firstly set a list.

List < string > myList = new List < string > ();
myList.Add("One");
myList.Add("Two");

Now declare a string array and use the CopyTo() method to copy.

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

Let us see the complete code to copy a list into a one-dimensional array.

Example

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

public class Demo {
   public static void Main() {
      List < string > myList = new List < string > ();
      myList.Add("One");
      myList.Add("Two");
      myList.Add("Three");
      myList.Add("Four");

      Console.WriteLine("First list...");
      foreach(string value in list1) {
         Console.WriteLine(value);
      }

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

      Console.WriteLine("After copy...");
      foreach(string value in arr) {
         Console.WriteLine(value);
      }
   }
}
raja
Published on 21-Aug-2018 08:22:59
Advertisements