首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> 關於.NET

LINQ Group By 操作完全指南:從基本分組到 Join 結合進階應用

     編輯:關於.NET

group ... by ... into 是 LINQ 分組查詢的核心語法,產生 IGrouping<TKey, TElement> 序列,每群組擁有 Key 屬性與可列舉的成員。

基本分組範例

var products = new[]
{
    new { ProductName = "Apple", Category = "Food" },
    new { ProductName = "Cat",   Category = "Animal" },
    new { ProductName = "Dog",   Category = "Other" },
    new { ProductName = "Pig",   Category = "Animal" }
};

var q = from p in products
        group p by p.Category into g
        orderby g.Key
        select g;

foreach (var group in q)
{
    Console.WriteLine(group.Key);           // Food, Animal, Other
    foreach (var item in group)
        Console.WriteLine($"\t{item.ProductName}");
}

輸出:

Food
    Apple
Animal
    Cat
    Pig
Other
    Dog

進階:Join 結合後再分組

情境:Northwind 資料庫,依類別名稱分組顯示產品。

NorthwindDataContext db = new NorthwindDataContext();
var products = db.Products;
var categories = db.Categories;

var query = from result in
            (from p in products.AsEnumerable()
             join c in categories.AsEnumerable()
             on p.CategoryID equals c.CategoryID   // 必須用 equals
             select new { CategoryName = c.CategoryName, Product = p })
            group result by result.CategoryName into g
            select g;

foreach (var group in query)
{
    Console.WriteLine(group.Key);
    foreach (var item in group)
        Console.WriteLine($"\t{item.Product.ProductName}");
}

關鍵注意事項

  • into 之後的範圍變數 (g) 代表群組,隱藏前面的範圍變數。
  • group 子句必須出現在 select 之前,或作為查詢的最後一個子句。
  • 針對資料庫查詢 (IQueryable) 使用 AsEnumerable() 將後續分組在記憶體執行,避免 SQL 轉譯限制。
  • Join 條件必須使用 equals 關鍵字,不可用 ==。

總結

  • 基本分組:group element by key into g。
  • 搭配 orderby g.Key 排序群組。
  • 進階組合:join 後 group,解決主從表分組顯示需求。
  • 群組物件同時具備 Key 與 IEnumerable<T> 雙重特性,遍歷極為直觀。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved