Home > Article > Backend Development > How to copy a collection to an array using C#?
Copy the collection into an array, first set it to −
List < string > list1 = new List < string > (); list1.Add("Car"); list1.Add("Bus"); list1.Add("Motorbike"); list1.Add("Train");
Now declare an array of strings and copy −
using the CopyTo() methodstring[] arr = new string[20]; list1.CopyTo(arr);
Let’s take a look at the complete code to copy a collection to an array −
using System; using System.Collections.Generic; using System.Linq; public class Demo { public static void Main() { List < string > list1 = new List < string > (); list1.Add("Car"); list1.Add("Bus"); list1.Add("Motobike"); list1.Add("Train"); 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); } } }
The above is the detailed content of How to copy a collection to an array using C#?. For more information, please follow other related articles on the PHP Chinese website!