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

当前回答

需要注意的一点是,您需要为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;
}

其他回答

您还可以使用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 })

虽然这个问题问的是按类属性分组,但如果你想对ADO对象(如DataTable)按多列分组,你必须将你的“新”项分配给变量:

EnumerableRowCollection<DataRow> ClientProfiles = CurrentProfiles.AsEnumerable()
                        .Where(x => CheckProfileTypes.Contains(x.Field<object>(ProfileTypeField).ToString()));
// do other stuff, then check for dups...
                    var Dups = ClientProfiles.AsParallel()
                        .GroupBy(x => new { InterfaceID = x.Field<object>(InterfaceField).ToString(), ProfileType = x.Field<object>(ProfileTypeField).ToString() })
                        .Where(z => z.Count() > 1)
                        .Select(z => z);

对于VB和匿名/lambda:

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