号外号外: 原[图享网]更名为 码友网(codedefault.com) 啦,感谢大家一路上的陪伴与支持。代码的世界里,码友网与大家一起同行!

.NET[C#]LINQ按多列分组(Group By)并计算总和(Sum)

.NET 作者: Rector 474阅读 0评论 0收藏 收藏本文 编辑

郑重申明:本文未经许可,禁止任何形式转载

.NET[C#]LINQ按多列分组(Group By)并计算总和(Sum),比如我们现在有类似的SQL语句:

SELECT * FROM <TableName> GROUP BY <Column1>,<Column2>
QuantityBreakdown
(
    MaterialID int,
    ProductID int,
    Quantity float
)

INSERT INTO @QuantityBreakdown (MaterialID, ProductID, Quantity)
SELECT MaterialID, ProductID, SUM(Quantity)
FROM @Transactions
GROUP BY MaterialID, ProductID

在C#中,如何使用LINQ实现以上SQL语句中的需求呢?方式归纳如下:

方式一

var query = (from t in Transactions
             group t by new {t.MaterialID, t.ProductID}
             into grp
                    select new
                    {
                        grp.Key.MaterialID,
                        grp.Key.ProductID,
                        Quantity = grp.Sum(t => t.Quantity)
                    }).ToList();

方式二

from grouping in list.GroupBy(x => new Tuple<string,string,string>(x.Person.LastName,x.Person.FirstName,x.Person.MiddleName))
select new SummaryItem
{
    LastName = grouping.Key.Item1,
    FirstName = grouping.Key.Item2,
    MiddleName = grouping.Key.Item3,
    DayCount = grouping.Count(), 
    AmountBilled = grouping.Sum(x => x.Rate),
}

方式三

var Results= query.GroupBy(x => new { x.Column1, x.Column2 });

阅读了该文章的人还浏览了...

本文永久链接码友网 » .NET[C#]LINQ按多列分组(Group By)并计算总和(Sum)

发布于: 2017-12-29 08:34:00
分享扩散:

文章评论

获取验证码