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)
           };
复制代码
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

苍狼_2001

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值