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

当前回答

var Results= query.GroupBy(f => new { /* add members here */  });

其他回答

var Results= query.GroupBy(f => new { /* add members here */  });

对于多列组,试试这个…

GroupBy(x=> new { x.Column1, x.Column2 }, (key, group) => new 
{ 
  Key1 = key.Column1,
  Key2 = key.Column2,
  Result = group.ToList() 
});

同样的方法,您可以添加Column3, Column4等。

对于VB和匿名/lambda:

query.GroupBy(Function(x) New With {Key x.Field1, Key x.Field2, Key x.FieldN })

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

.GroupBy(x => x.Column1 + " " + x.Column2)