How to copy a List collection to an array?


To copy a C# list collection to an array, firstly set a list −

List <string> list1 = new List <string> ();
list1.Add("One");
list1.Add("Two");
list1.Add("Three");
list1.Add("Four");

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

string[] arr = new string[20];
list1.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> list1 = new List <string> ();
      list1.Add("One");
      list1.Add("Two");
      list1.Add("Three");
      list1.Add("Four");

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

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

      Console.WriteLine("After copy...");

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

karthikeya Boyini
karthikeya Boyini

I love programming (: That's all I know

Updated on: 21-Jun-2020

541 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements