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

其他回答

group x by new {x. col, x. col}

程序样例:

.GroupBy(x => new { x.Column1, x.Column2 })

您还可以使用Tuple<>作为强类型分组。

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),
}

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

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

or

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

对于多列组,试试这个…

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

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