如何在 LINQ 中执行 GroupBy 多列
SQL 中与此类似的东西:
SELECT * FROM <TableName> GROUP BY <Column1>,<Column2>
如何将其转换为 LINQ:
QuantityBreakdown
(
MaterialID int,
ProductID int,
Quantity float
)
INSERT INTO @QuantityBreakdown (MaterialID, ProductID, Quantity)
SELECT MaterialID, ProductID, SUM(Quantity)
FROM @Transactions
GROUP BY MaterialID, ProductID
使用匿名类型。
例如
group x by new { x.Column1, x.Column2 }
程序样本
.GroupBy(x => new { x.Column1, x.Column2 })
好吧得到这个:
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();