共用方式為


以方法為基礎的查詢語法範例:排序

本主題中的範例示範如何使用 ThenBy 方法,透過以方法為基礎的查詢語法來查詢 AdventureWorks 銷售模型。 這些範例中使用的 AdventureWorks Sales Model 是從 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

範例

下列以方法為基礎的查詢語法範例會使用 OrderByThenBy 來傳回先依據姓氏再依據名字排序的連絡人清單。

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

範例

下列範例會使用 OrderByThenByDescending 方法,先依據標價排序,然後再執行產品名稱的遞減排序。

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

另請參閱