按多列分组

我怎么能在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 

使用匿名types。

例如

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

程序样本

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

确定这是:

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

对于按多列分组,试试这个,而不是…

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

同样可以添加Column3,Column4等

您也可以使用Tuple <>来进行强types分组。

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

以为这个问题是关于按类属性分组的问题,如果你想对ADO对象(如DataTable)进行多列分组,你必须将你的“新”项分配给variables:

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

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

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

要么

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

组x由新{x.Col,x.Col}

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