共用方式為


以方法為基礎的查詢語法範例:排序 (LINQ to Entities)

本主題中的範例將示範如何使用 ThenBy 方法,透過以方法為基礎的查詢語法來查詢 AdventureWorks Sales Model。 這些範例中使用的 AdventureWorks Sales Model 是從 AdventureWorks 範例資料庫中的 Contact、Address、Product、SalesOrderHeader 和 SalesOrderDetail 資料表所建立。

此主題中的範例將使用下列 using/Imports 陳述式:

Option Explicit On
Option Strict On
Imports L2EExamplesVB.AdventureWorksModel
Imports System.Data.Objects
Imports System.Globalization
using System;
using System.Data;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Objects;
using AdventureWorksModel;
using System.Globalization;

如需詳細資訊,請參閱 HOW TO:在 Visual Studio 中建立 LINQ to Entities 專案

ThenBy

範例

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

Using AWEntities As New AdventureWorksEntities

    Dim sortedContacts = AWEntities.Contact _
    .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
using (AdventureWorksEntities AWEntities = new AdventureWorksEntities())
{
    IQueryable<Contact> sortedContacts = AWEntities.Contact
        .OrderBy(c => c.LastName)
        .ThenBy(c => c.FirstName)
        .Select(c => c);

    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);
    }
}

ThenByDescending

範例

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

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

    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
using (AdventureWorksEntities AWEntities = new AdventureWorksEntities())
{
    ObjectQuery<Product> products = AWEntities.Product;

    IOrderedQueryable<Product> query = 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);
    }
}

另請參閱

概念

以方法為基礎的查詢語法範例 (LINQ to Entities)