Group By Multiple Columns

Sreedhar picture Sreedhar · May 11, 2009 · Viewed 605.7k times · Source

How can I do GroupBy Multiple Columns in LINQ

Something similar to this in SQL:

SELECT * FROM <TableName> GROUP BY <Column1>,<Column2>

How can I convert this to 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

Answer

leppie picture leppie · May 11, 2009

Use an anonymous type.

Eg

group x by new { x.Column1, x.Column2 }