How To Copy A C# List

C# List<T> class provides methods and properties to create a list of objects (classes).
 
List is a generic class. You must import the following namespace before using the List<T> class.
  1. using System.Collections.Generic;  
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.
  1. using System;  
  2. using System.Collections.Generic;  
  3. namespace ConsoleApp1  
  4. {  
  5.     class Program  
  6.     {  
  7.         static void Main(string[] args)  
  8.         {  
  9.             List<string> AuthorList = new List<string>();  
  10.             AuthorList.Add("Mahesh Chand");  
  11.             AuthorList.Add("Praveen Kumar");  
  12.             AuthorList.Add("Raj Kumar");  
  13.             AuthorList.Add("Nipun Tomar");  
  14.             AuthorList.Add("Dinesh Beniwal");  
  15.             AuthorList.Add("Mahesh Chand");  
  16.             AuthorList.Add("Praveen Kumar");  
  17.             AuthorList.Add("Raj Kumar");  
  18.             AuthorList.Add("Nipun Tomar");  
  19.             AuthorList.Add("Dinesh Beniwal");  
  20.             // Create an array of strings  
  21.             string[] authorArray = new string[15];  
  22.             // Copy entire List  
  23.             AuthorList.CopyTo(authorArray);  
  24.             // Copy items starting at index = 4  
  25.             AuthorList.CopyTo(authorArray, 4);  
  26.             // Copy 4 items starting at index 2 in List and copying  
  27.             // to array starting at index 10  
  28.             AuthorList.CopyTo(2, authorArray, 3, 4);  
  29.             foreach (string author in authorArray)  
  30.             {  
  31.                 Console.WriteLine(author);  
  32.             }  
  33.         }  
  34.     }  
  35. }  
The output from above code listing is shown in below figure.
 
Copy C# List 

Similar Articles
Mindcracker
Founded in 2003, Mindcracker is the authority in custom software development and innovation. We put best practices into action. We deliver solutions based on consumer and industry analysis.