ToArray
This method converts types to arrays. It forces the evaluation of query expressions and IEnumerable
types. It returns an array of the same type.
Implemented in System.Linq
, ToArray
reduces program length and increases program simplicity. But we must be careful not to call ToArray
when it is not needed.
The ToArray
extension method is a generic method that internally allocates a Buffer
array where the elements are copied. We often use it alongside query expressions.
int
elements.var
for the type of the query expression.ToArray()
forces evaluation. The int[]
variable is assigned to the memory allocated on the managed heap by ToArray
.ToArray()
with a foreach
loop, printing it to the console.using System; using System.Linq; // Step 1: create an array. int[] array1 = { 5, 1, 4 }; // Step 2: use query expression on array. var query = from element in array1 orderby element select element; // Step 3: convert expression to array variable. int[] array2 = query.ToArray(); // Step 4: display array. foreach (int value in array2) { Console.WriteLine(value); }1 4 5
ToArray
, same statementSuppose we have a query expression, and we want to have an array. We can call ToArray
directly on the query expression, which forces its evaluation.
ToArray
, Average()
, and Sum()
, we often want to directly invoke the extension method on a query.using System; using System.Linq; class Program { static void PrintArrayLength(int[] array) { Console.WriteLine("ARRAY LENGTH: {0}", array.Length); } static void Main() { int[] elements = { 10, 20, 30 }; // Use ToArray directly on query. PrintArrayLength((from e in elements where e >= 20 select e).ToArray()); } }ARRAY LENGTH: 2
We can sometimes avoid using ToArray
. Suppose want to Join
together the strings in a string
List
. We can directly pass the List
to string.Join
.
ToArray
and then pass the array to Join()
, but this will not give us any advantage.ToArray
when we do not need to can cause a performance loss (one that is proportional to the element count).using System; using System.Collections.Generic; class Program { static void Main() { var items = new List<string>() { "test", "deploy", "script" }; // We can use string.Join without ToArray. Console.WriteLine("NO TOARRAY: {0}", string.Join("+", items)); Console.WriteLine(" TOARRAY: {0}", string.Join("+", items.ToArray())); } }NO TOARRAY: test+deploy+script TOARRAY: test+deploy+script
There are other ToArray
methods. It is important to realize that the "ToArray
" method identifier is used by various different implementations on different types.
List
generic type has a ToArray
method that is implemented on the List
type.ToArray
extension method on the List
type, which does the same thing but has some performance disadvantages.ArrayList
class
contains a ToArray
method that is implemented on its custom type.ToArray
converts an enumerable types into an array. It can act upon a query expression variable. It forces evaluation of a query expression.