基于方法的查询语法示例:转换
本主题中的示例演示如何使用 ToArrayToDictionary 和 ToList 方法,利用基于方法的查询语法来查询 AdventureWorks 销售模型。 这些示例中使用的 AdventureWorks 销售模型从 AdventureWorks 示例数据库中的 Contact、Address、Product、SalesOrderHeader 和 SalesOrderDetail 等表生成。
本主题中的示例使用下面的 using
/Imports
语句:
using System;
using System.Data;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Objects;
using System.Globalization;
using System.Data.EntityClient;
using System.Data.SqlClient;
using System.Data.Common;
Option Explicit On
Option Strict On
Imports System.Data.Objects
Imports System.Globalization
ToArray
示例
以下示例使用 ToArray 方法以立即将序列转换为数组。
using (AdventureWorksEntities context = new AdventureWorksEntities())
{
ObjectSet<Product> products = context.Products;
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);
}
}
Using context As New AdventureWorksEntities
Dim products As ObjectSet(Of Product) = context.Products
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
ToDictionary
示例
以下示例使用 ToDictionary 方法以立即将序列和相关的键表达式转换为字典。
using (AdventureWorksEntities context = new AdventureWorksEntities())
{
ObjectSet<Product> products = context.Products;
Dictionary<String, Product> scoreRecordsDict = products.
ToDictionary(record => record.Name);
Console.WriteLine("Top Tube's ProductID: {0}",
scoreRecordsDict["Top Tube"].ProductID);
}
Using context As New AdventureWorksEntities
Dim products As ObjectSet(Of Product) = context.Products
Dim scoreRecordsDict As Dictionary(Of String, Product) = _
products.ToDictionary(Function(record) record.Name)
Console.WriteLine("Top Tube's ProductID: {0}", _
scoreRecordsDict("Top Tube").ProductID)
End Using
ToList
示例
以下示例使用 ToList 方法以立即将序列转换为 List<T>,其中,T
属于类型 DataRow。
using (AdventureWorksEntities context = new AdventureWorksEntities())
{
ObjectSet<Product> products = context.Products;
List<Product> query =
(from product in products
orderby product.Name
select product).ToList();
Console.WriteLine("The product list, ordered by product name:");
foreach (Product product in query)
{
Console.WriteLine(product.Name.ToLower(CultureInfo.InvariantCulture));
}
}
Using context As New AdventureWorksEntities
Dim products As ObjectSet(Of Product) = context.Products
Dim prodList As List(Of Product) = ( _
From product In products _
Order By product.Name _
Select product).ToList()
Console.WriteLine("The product list, ordered by product name:")
For Each prod As Product In prodList
Console.WriteLine(prod.Name.ToLower(CultureInfo.InvariantCulture))
Next
End Using