按多列分组

如何在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 @TransactionsGROUP BY MaterialID, ProductID
732922 次浏览

使用匿名类型。

eg

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

OK得到了这个:

var query = (from t in Transactionsgroup t by new {t.MaterialID, t.ProductID}into grpselect new{grp.Key.MaterialID,grp.Key.ProductID,Quantity = grp.Sum(t => t.Quantity)}).ToList();

程序示例:

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

您还可以将元组<>用于强类型分组。

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

对于按多列分组,请改为尝试此操作…

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

同样的方式,你可以添加列3,列4等。

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

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

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

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

用new{x. Col, x. Col}将x分组

.GroupBy(x => (x.MaterialID, x.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;}

C#7.1或更高使用TuplesInferred tuple element names(目前它只适用于linq to objects,当需要表达式树时不支持,例如someIQueryable.GroupBy(...).github问题):

// declarative query syntaxvar result =from x in inMemoryTablegroup x by (x.Column1, x.Column2) into gselect (g.Key.Column1, g.Key.Column2, QuantitySum: g.Sum(x => x.Quantity));
// or method syntaxvar 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 syntaxvar result3 =from x in tablegroup x by new { x.Column1, x.Column2 } into gselect new { g.Key.Column1, g.Key.Column2, QuantitySum = g.Sum(x => x.Quantity) };
// or method syntaxvar result4 = table.GroupBy(x => new { x.Column1, x.Column2 }).Select(g =>new { g.Key.Column1, g.Key.Column2 , QuantitySum= g.Sum(x => x.Quantity) });

对于VB匿名/lambda

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