共用方式為


HOW TO:排序 Join 子句的結果 (C# 程式設計手冊)

更新:2007 年 11 月

這個範例會示範如何排序聯結作業的結果。請注意,在聯結後才會進行排序。雖然您可以在聯結之前搭配一個或多個來源序列 (Sequence) 使用 orderby 子句,但是我們通常不建議這種做法。一些 LINQ 提供者可能不會保留在聯結後的排序。

範例

這個查詢會建立群組聯結,並接著根據仍在範圍中的分類項目來排序這些群組。在匿名型別初始設定式內,子查詢 (Subquery) 會排序產品序列中的所有相符項目。

class HowToOrderJoins
{
    #region Data
    class Product
    {
        public string Name { get; set; }
        public int CategoryID { get; set; }
    }

    class Category
    {
        public string Name { get; set; }
        public int ID { get; set; }
    }

    // Specify the first data source.
    List<Category> categories = new List<Category>()
    { 
        new Category(){Name="Beverages", ID=001},
        new Category(){ Name="Condiments", ID=002},
        new Category(){ Name="Vegetables", ID=003},
        new Category() {  Name="Grains", ID=004},
        new Category() {  Name="Fruit", ID=005}            
    };

    // Specify the second data source.
    List<Product> products = new List<Product>()
   {
      new Product{Name="Cola",  CategoryID=001},
      new Product{Name="Tea",  CategoryID=001},
      new Product{Name="Mustard", CategoryID=002},
      new Product{Name="Pickles", CategoryID=002},
      new Product{Name="Carrots", CategoryID=003},
      new Product{Name="Bok Choy", CategoryID=003},
      new Product{Name="Peaches", CategoryID=005},
      new Product{Name="Melons", CategoryID=005},
    };
    #endregion
    static void Main()
    {
        HowToOrderJoins app = new HowToOrderJoins();
        app.OrderJoin1();

        // Keep console window open in debug mode.
        Console.WriteLine("Press any key to exit.");
        Console.ReadKey();

    }

    void OrderJoin1()
    {
        var groupJoinQuery2 =
            from category in categories
            join prod in products on category.ID equals prod.CategoryID into prodGroup
            orderby category.Name
            select new
            {
                Category = category.Name,
                Products = from prod2 in prodGroup
                           orderby prod2.Name
                           select prod2
            };

        foreach (var productGroup in groupJoinQuery2)
        {
            Console.WriteLine(productGroup.Category);
            foreach (var prodItem in productGroup.Products)
            {
                Console.WriteLine("  {0,-10} {1}", prodItem.Name, prodItem.CategoryID);
            }
        }
    }
    /* Output:
        Beverages
          Cola       1
          Tea        1
        Condiments
          Mustard    2
          Pickles    2
        Fruit
          Melons     5
          Peaches    5
        Grains
        Vegetables
          Bok Choy   3
          Carrots    3
     */
}

編譯程式碼

  • 建立以 .NET Framework 3.5 版為目標的 Visual Studio 專案。根據預設,該專案具有 System.Core.dll 的參考,以及 System.Linq 命名空間的 using 指示詞。

  • 將程式碼複製至您的專案中。

  • 按 F5 編譯和執行程式。

  • 按任何鍵離開主控台視窗。

請參閱

概念

LINQ 查詢運算式 (C# 程式設計手冊)

聯結作業

參考

orderby 子句 (C# 參考)

join 子句 (C# 參考)