C# List CopyTo ExamplesUse the CopyTo method on the List type to copy a List to an array.
CopyTo. This C# method copies List elements to an array. It provides a way to do this in one declarative function call—this keeps code simpler.
Method notes. When using the CopyTo() method, we must make sure the target array is properly allocated. And the element types must match.
Complex example. To begin, we have a List of ints and we call its CopyTo method with an index argument. Copying begins in the array at the argument index.
Important With this overload, we copy from the List at its start, but into the array at the specified index.
C# program that uses CopyTo with index
using System; using System.Collections.Generic; class Program { static void Main() { var list = new List<int>() { 10, 20, 30 }; int[] array = new int[5]; // Use CopyTo to copy into an array starting at a certain index. // .. The entire list is copied. list.CopyTo(array, 2); Console.WriteLine("LIST: " + string.Join(",", list)); Console.WriteLine("ARRAY: " + string.Join(",", array)); } }
LIST: 10,20,30 ARRAY: 0,0,10,20,30
Simple example. This program creates a List with three elements in it: the values 5, 6 and 7. Next an int array is allocated. It has a length equal to the Count of the List.
Int Array
Info The CopyTo method is invoked upon the list variable. The array now contains all the elements of the originating List.
C# program that uses CopyTo on List
using System; using System.Collections.Generic; class Program { static void Main() { // Create a list with 3 elements. var list = new List<int>() { 5, 6, 7 }; // Create an array with length of 3. int[] array = new int[list.Count]; // Copy the list to the array. list.CopyTo(array); // Display. Console.WriteLine(array[0]); Console.WriteLine(array[1]); Console.WriteLine(array[2]); } }
5 6 7
Internals. CopyTo() calls Array.Copy on the internal array inside the List. Examining the secrets inside .NET implementations helps us learn good practices.
Note The .NET developers probably know more about the best way to do things than do most of us.
Summary. The List CopyTo method provides a way to copy all the elements of a List to a compatible and allocated array. The array must have adequate space for all the elements.
Elements, review. The type of the elements in the array must be equivalent to the type of the List elements. Our code must have a correct target array.
© 2007-2021 sam allen.
see site info on the changelog.