The CopyTo method copies a List into a one-dimensional array. CopyTo can also copy a partial list or a number of items form a list to another collection. The following code copies a list into an Array.
using System; using System.Collections.Generic; namespace ConsoleApp1 { class Program { static void Main(string[] args) { List<string> AuthorList = new List<string>(); AuthorList.Add("Mahesh Chand"); AuthorList.Add("Praveen Kumar"); AuthorList.Add("Raj Kumar"); AuthorList.Add("Nipun Tomar"); AuthorList.Add("Dinesh Beniwal"); AuthorList.Add("Mahesh Chand"); AuthorList.Add("Praveen Kumar"); AuthorList.Add("Raj Kumar"); AuthorList.Add("Nipun Tomar"); AuthorList.Add("Dinesh Beniwal"); // Create an array of strings string[] authorArray = new string[15]; // Copy entire List AuthorList.CopyTo(authorArray); // Copy items starting at index = 4 AuthorList.CopyTo(authorArray, 4); // Copy 4 items starting at index 2 in List and copying // to array starting at index 10 AuthorList.CopyTo(2, authorArray, 3, 4); foreach (string author in authorArray) { Console.WriteLine(author); } } } }
In the above code, the first CopyTo copies the entire list. The second CopyTo method copies all items starting at index 4 and the third CopyTo method copies a partial list.
The output from the above code listing is shown in the below figure.
Next >> C# List Tutorial