How to copy a C# List

The CopyTo method copies a List into a one-dimensional array. The CopyTo method has three overloaded forms. 

The following code snippet copies the entire list into an Array. 

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);
}

Download Free book: Programming List with C#