1104

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

14 回答 14

1326

使用匿名类型。

例如

group x by new { x.Column1, x.Column2 }
于 2009-05-11T07:37:04.133 回答
861

程序样本:

.GroupBy(x => new { x.Column1, x.Column2 })
于 2012-02-07T13:55:24.857 回答
513

好的,这是:

var query = (from t in Transactions
             group t by new {t.MaterialID, t.ProductID}
             into grp
                    select new
                    {
                        grp.Key.MaterialID,
                        grp.Key.ProductID,
                        Quantity = grp.Sum(t => t.Quantity)
                    }).ToList();
于 2009-05-11T09:50:30.377 回答
177

对于按多列分组,请改用此方法...

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

同样的方式你可以添加 Column3、Column4 等。

于 2015-12-30T08:06:46.337 回答
47

从 C# 7 开始,您还可以使用值元组:

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

或者

.GroupBy(x => (x.Column1, x.Column2))
于 2017-03-14T14:59:39.757 回答
39

使用Tuplesand的 C# 7.1 或更高Inferred tuple element names版本(目前它仅适用于linq to objects并且在需要表达式树时不受支持,例如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 或更高版本使用anonymous types

// 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) });
于 2019-02-09T10:00:06.737 回答
19

您还可以使用 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),
}
于 2015-12-29T20:14:34.003 回答
8

虽然这个问题询问的是按类属性分组,但如果您想针对 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);
于 2013-11-12T18:26:02.547 回答
3
var Results= query.GroupBy(f => new { /* add members here */  });
于 2016-05-16T11:26:36.800 回答
3

需要注意的是,您需要为 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;
}
于 2018-04-26T20:53:09.390 回答
2
.GroupBy(x => x.Column1 + " " + x.Column2)
于 2017-05-19T06:41:11.610 回答
2

将 x 按新 { x.Col, x.Col} 分组

于 2017-10-23T15:14:22.767 回答
2

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

于 2017-12-27T11:36:38.880 回答
2

对于VB匿名/lambda

query.GroupBy(Function(x) New With {Key x.Field1, Key x.Field2, Key x.FieldN })
于 2020-05-06T12:05:09.600 回答