C# ToArray Extension Method

Use the ToArray extension method from System.Linq. Convert a query, or any IEnumerable, into an array.


converts types to arrays. It forces the evaluation of query expressions and IEnumerable types. Implemented in System.Linq, it reduces program length and increases program simplicity.IEnumerable


This program shows a query expression using the query syntax. The program takes an input integer array. It then sorts it using the LINQ syntax, which internally drills down to a quick sort.

Note: The query is not immediately executed. But the ToArray method forces its evaluation (with iteration) into an array variable.

Array: In an array, elements are stored in contiguous memory on the managed heap. The program then displays these sorted array elements.

C# program that uses ToArray extension method using System; using System.Linq; class Program { static void Main() { // // An example array. // int[] array1 = { 5, 4, 1, 2, 3 }; // // Use query expression on array. // var query = from element in array1 orderby element select element; // // Convert expression to array variable. // int[] array2 = query.ToArray(); // // Display array. // foreach (int value in array2) { Console.WriteLine(value); } } } Output 1 2 3 4 5

In this example,

var is a perfect fit for the query expression that declares a sort of the array input element integers. After the query expression is declared and the supporting data structures are stored in memory, it is executed.Var


the ToArray method forces evaluation. The second int[] local variable is assigned to the memory allocated on the managed heap by the internal implementation of the ToArray method.Int Array

Tip: The ToArray extension method is a generic method that internally allocates a Buffer array where the elements are copied.

Generic Class, Method


There are other ToArray methods in the .NET Framework. It is important to realize that the "ToArray" method identifier is used by various different implementations on different types.

Note: The List generic type has a ToArray method that is implemented on the List type.


However: You can invoke the ToArray extension method on the List type, which does the same thing but has some performance disadvantages.

Convert List, Array

Also: The ArrayList class contains a ToArray method that is implemented on its custom type.



ToArray converts an enumerable types into an array. This extension method is part of the System.Linq namespace. It can act upon a query expression variable. It forces evaluation of a query expression.
Dot Net Perls
© 2007-2019 Sam Allen. All rights reserved. Written by Sam Allen,