LINQ系列:Linq to Object分組操作符

libingql發表於2014-10-22

  分組是指根據一個特定的值將序列中的值或元素進行分組。LINQ只包含一個分組操作符:GroupBy。

GroupBy

1>. 原型定義

public static IQueryable<IGrouping<TKey, TSource>> GroupBy<TSource, TKey>(this IQueryable<TSource> source, Expression<Func<TSource, TKey>> keySelector);

2>. 示例

var expr = from p in context.Products
            group p by p.CategoryID;

foreach (var item in expr)
{
    foreach (var p in item)
    {
        Console.WriteLine(p.ProductName);
    }
}
var expr = context.Cities.GroupBy(c => c.ProvinceID);
var expr = from p in context.Products
           group new { p.ProductID, p.CategoryID, p.ProductName }
           by p.CategoryID;
var expr = context.Products
    .GroupBy(p => p.CategoryID,
    p => new
    {
        p.ProductID,
        p.CategoryID,
        p.ProductName
    });

  根據產品的分類ID分組,查詢產品數大於5的分類ID和產品數:

var expr = from p in context.Products
           group p by p.CategoryID into g
           where g.Count() > 5
           orderby g.Count() descending
           select new
           {
               分類ID = g.Key,
               產品數 = g.Count()
           };
SELECT 
    [GroupBy1].[K1] AS [CategoryID], 
    [GroupBy1].[A3] AS [C1]
    FROM ( SELECT 
        [Extent1].[CategoryID] AS [K1], 
        COUNT(1) AS [A1], 
        COUNT(1) AS [A2], 
        COUNT(1) AS [A3]
        FROM [dbo].[Product] AS [Extent1]
        GROUP BY [Extent1].[CategoryID]
    )  AS [GroupBy1]
    WHERE [GroupBy1].[A1] > 5
    ORDER BY [GroupBy1].[A2] DESC
var expr = from p in context.Products
           group p by p.CategoryID into g
           select new
           {
               CategoryID = g.Key,
               ProductCount = g.Count()
           };
var expr = from p in context.Products
           group p by p.CategoryID into g
           select new
           {
               CategoryID = g.Key,
               TotalUnitsInStock = g.Sum(p => p.UnitsInStock)
           };
var expr = from p in context.Products
           group p by p.CategoryID into g
           select new
           {
               CategoryID = g.Key,
               CheapestUnitPrice = g.Min(p => p.UnitPrice)
           };
var expr = from p in context.Products
           group p by p.CategoryID into g
           let cheapestUnitPrice = g.Min(p => p.UnitPrice)
           select new
           {
               CategoryID = g.Key,
               CheapestProducts = g.Where(p => p.UnitPrice == cheapestUnitPrice)
           };

相關文章