基于方法的查询语法示例:中间件排序
本主题中的示例演示如何使用 ThenBy 方法通过基于方法的查询语法来查询 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
ThenBy
示例
采用基于方法的查询语法的以下示例使用 OrderBy 和 ThenBy 以返回先按姓氏后按名字排序的联系人列表。
using (AdventureWorksEntities context = new AdventureWorksEntities())
{
IQueryable<Contact> sortedContacts = context.Contacts
.OrderBy(c => c.LastName)
.ThenBy(c => c.FirstName);
Console.WriteLine("The list of contacts sorted by last name then by first name:");
foreach (Contact sortedContact in sortedContacts)
{
Console.WriteLine(sortedContact.LastName + ", " + sortedContact.FirstName);
}
}
Using context As New AdventureWorksEntities
Dim sortedContacts = context.Contacts _
.OrderBy(Function(c) c.LastName) _
.ThenBy(Function(c) c.FirstName) _
.Select(Function(c) c)
Console.WriteLine("The list of contacts sorted by last name then by first name:")
For Each sortedContact As Contact In sortedContacts
Console.WriteLine(sortedContact.LastName + ", " + sortedContact.FirstName)
Next
End Using
ThenByDescending
示例
以下示例使用 OrderBy 和 ThenByDescending 方法以首先按标价排序,然后执行产品名称的降序排序。
using (AdventureWorksEntities context = new AdventureWorksEntities())
{
IOrderedQueryable<Product> query = context.Products
.OrderBy(product => product.ListPrice)
.ThenByDescending(product => product.Name);
foreach (Product product in query)
{
Console.WriteLine("Product ID: {0} Product Name: {1} List Price {2}",
product.ProductID,
product.Name,
product.ListPrice);
}
}
Using context As New AdventureWorksEntities
Dim products As ObjectSet(Of Product) = context.Products
Dim query As IOrderedQueryable(Of Product) = products _
.OrderBy(Function(prod As Product) prod.ListPrice) _
.ThenByDescending(Function(prod As Product) prod.Name)
For Each prod As Product In query
Console.WriteLine("Product ID: {0} Product Name: {1} List Price {2}", _
prod.ProductID, _
prod.Name, _
prod.ListPrice)
Next
End Using