Home
Map
List CopyTo ExamplesUse the CopyTo method on the List type to copy a List to an array.
C#
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.
Shows a method
Method notes. When using the CopyTo() method, we must make sure the target array is properly allocated. And the element types must match.
List
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.
Shows a method
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.
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.
Array.Copy
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.
C#VB.NETPythonGoJavaSwiftRust
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
No updates found for this page.
Home
Changes
© 2007-2023 Sam Allen.