来源:https://codedefault.com/2018/group-by-multiple-columns-and-sum-in-csharp
.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 });
易错提醒:
grp.Key.ProductID, //前往不要忘了Key!!!
Quantity = grp.Sum(t => t.Quantity) //必须取别名Quantity !!!