Ads Top

How to copy a C# List

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

List<string> AuthorList = new List<string>();
AuthorList.Add("Qasim");
AuthorList.Add("Adil");
AuthorList.Add("Umer");
AuthorList.Add("Abdullah");

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

Powered by Blogger.