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

  分组是指根据一个特定的值将序列中的值或元素进行分组。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)
           };

你可能感兴趣的:(object)