
Copy the collection into an array, first set it to −
1 2 3 4 5 | List < string > list1 = new List < string > ();
list1.Add( "Car" );
list1.Add( "Bus" );
list1.Add( "Motorbike" );
list1.Add( "Train" );
|
Copy after login
Now declare an array of strings and copy −
using the CopyTo() method
1 2 | string[] arr = new string[20];
list1.CopyTo(arr);
|
Copy after login
Let’s take a look at the complete code to copy a collection to an array −
Example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | 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);
}
}
}
|
Copy after login
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!