如何在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

当前回答

从c# 7开始,你也可以使用值元组:

group x by (x.Column1, x.Column2)

or

.GroupBy(x => (x.Column1, x.Column2))

其他回答

使用匿名类型。

Eg

group x by 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();

c# 7.1或更高版本,使用元组和推断元组元素名称(目前它只适用于对象的linq,当需要表达式树时不支持,例如someIQueryable.GroupBy(…)Github的问题):

// declarative query syntax
var result = 
    from x in inMemoryTable
    group x by (x.Column1, x.Column2) into g
    select (g.Key.Column1, g.Key.Column2, QuantitySum: g.Sum(x => x.Quantity));

// or method syntax
var result2 = inMemoryTable.GroupBy(x => (x.Column1, x.Column2))
    .Select(g => (g.Key.Column1, g.Key.Column2, QuantitySum: g.Sum(x => x.Quantity)));

使用匿名类型的c# 3或更高版本:

// declarative query syntax
var result3 = 
    from x in table
    group x by new { x.Column1, x.Column2 } into g
    select new { g.Key.Column1, g.Key.Column2, QuantitySum = g.Sum(x => x.Quantity) };

// or method syntax
var result4 = table.GroupBy(x => new { x.Column1, x.Column2 })
    .Select(g => 
      new { g.Key.Column1, g.Key.Column2 , QuantitySum= g.Sum(x => x.Quantity) });

.GroupBy(x => (x.MaterialID, x. producd))

从c# 7开始,你也可以使用值元组:

group x by (x.Column1, x.Column2)

or

.GroupBy(x => (x.Column1, x.Column2))