C# ToArray

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.

ArrayIEnumerable

Example

LINQ: language integrated query

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.

SortIterate

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.

Console.WriteLine
Based on:

.NET 4.5

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
Var keyword

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.

VarThe C# programming language

Next, 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 Method

Discussion

Squares: abstract

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.

List

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.

ArrayList

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.


C#: LINQ