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

当前回答

程序样例:

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

其他回答

需要注意的一点是,您需要为Lambda表达式发送一个对象,而不能为类使用实例。

例子:

public class Key
{
    public string Prop1 { get; set; }

    public string Prop2 { get; set; }
}

这将进行编译,但每个循环将生成一个键。

var groupedCycles = cycles.GroupBy(x => new Key
{ 
  Prop1 = x.Column1, 
  Prop2 = x.Column2 
})

如果你不想命名键属性,然后检索它们,你可以这样做。这将正确地GroupBy并为您提供关键属性。

var groupedCycles = cycles.GroupBy(x => new 
{ 
  Prop1 = x.Column1, 
  Prop2= x.Column2 
})

foreach (var groupedCycle in groupedCycles)
{
    var key = new Key();
    key.Prop1 = groupedCycle.Key.Prop1;
    key.Prop2 = groupedCycle.Key.Prop2;
}

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

对于多列组,试试这个…

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

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

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

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