How to: Convert the Results of a LINQ Query to an Array
Use the ToArray method to create an array from results of a LINQ query. Calling ToArray also forces immediate execution of the query. The following example uses the ToArray method to immediately evaluate the query and convert the sequence into an array.
To run the code in this example, you need a fluent model based on the Northwind database.
The following code is the LINQ example.
using ( FluentModel dbContext = new FluentModel() )
{
IQueryable<Product> products = from p in dbContext.Products
orderby p.ProductName descending
select p;
Product[] productsArray = products.ToArray();
foreach ( Product product in productsArray )
{
Console.WriteLine( product.ProductName );
}
}
Using dbContext As New FluentModel()
Dim products As IQueryable(Of Product) = From p In dbContext.Products
Order By p.ProductName Descending
Select p
Dim productsArray() As Product = products.ToArray()
For Each _product As Product In productsArray
Console.WriteLine(_product.ProductName)
Next _product
End Using