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

.NET 作者: Rector 发布时间: 2017-12-29 08:34:00 21阅读 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)

分享扩散:

文章评论

获取验证码