C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Var: We use var for the type of the query expression that declares a sort of the array input element integers.
VarNote: 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 ArrayTip: The ToArray extension method is a generic method that internally allocates a Buffer array where the elements are copied.
Generic Class, MethodC# 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
Tip: For methods like ToArray, Average(), and Sum(), we often want to directly invoke the extension method on a query.
AverageSumC# program that uses ToArray directly on 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());
}
}
Output
ARRAY LENGTH: 2
Note: We can call ToArray and then pass the array to Join(), but this will not give us any advantage.
And: Using ToArray when we do not need to can cause a performance loss (one that is proportional to the element count).
C# program that avoids ToArray
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()));
}
}
Output
NO TOARRAY: test+deploy+script
TOARRAY: test+deploy+script
Note: The List generic type has a ToArray method that is implemented on the List type.
ListHowever: You can invoke the ToArray extension method on the List type, which does the same thing but has some performance disadvantages.
Convert List, ArrayAlso: The ArrayList class contains a ToArray method that is implemented on its custom type.
ArrayList