C# ToArray Extension Method

Use the ToArray extension method from System.Linq. Convert a query, or any IEnumerable, into an array.
ToArray 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.IEnumerableLINQ
Example. 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.

Var: We use var for the type of the query expression that declares a sort of the array input element integers.


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

Next: ToArray() forces evaluation. The second int[] variable is assigned to the memory allocated on the managed heap by ToArray.

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
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
Discussion. 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.

Summary. 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.
© 2007-2019 Sam Allen. Every person is special and unique. Send bug reports to
Dot Net Perls