共用方式為


How to: Convert the Results of a LINQ to Entities Query to an Array

Use the ToArray method to create an array from the results of a LINQ to Entities query. Calling ToArray also forces immediate execution of the query. For examples of converting the results of a LINQ to Entities query to a Dictionary or List, see Method-Based Query Syntax Examples: Conversion (LINQ to Entities).

Example

The following example uses the ToArray method to immediately evaluate the query and convert the sequence into an array.

Using AWEntities As New AdventureWorksEntities
    Dim products As ObjectQuery(Of Product) = AWEntities.Product

    Dim prodArray As Product() = ( _
        From product In products _
        Order By product.ListPrice Descending _
        Select product).ToArray()

    Console.WriteLine("The list price from highest to lowest:")
    For Each prod As Product In prodArray
        Console.WriteLine(prod.ListPrice)
    Next
End Using
using (AdventureWorksEntities AWEntities = new AdventureWorksEntities())
{
    ObjectQuery<Product> products = AWEntities.Product;

    Product[] prodArray = (
        from product in products
        orderby product.ListPrice descending
        select product).ToArray();

    Console.WriteLine("Every price from highest to lowest:");
    foreach (Product product in prodArray)
    {
        Console.WriteLine(product.ListPrice);
    }
}

Compiling the Code

The example in this topic contains references to objects and namespaces that are defined in the sample project in How to: Create a LINQ to Entities Project in Visual Studio. To compile and run this example, paste it into the Main method.

See Also

Concepts

Method-Based Query Syntax Examples: Conversion (LINQ to Entities)

Other Resources

Querying an Entity Data Model (Entity Framework Tasks)