C# 按多列分组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/847066/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Group By Multiple Columns
提问by Sreedhar
How can I do GroupBy Multiple Columns in LINQ
如何在 LINQ 中按多列进行分组
Something similar to this in SQL:
SQL 中与此类似的内容:
SELECT * FROM <TableName> GROUP BY <Column1>,<Column2>
How can I convert this to LINQ:
如何将其转换为 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
采纳答案by leppie
Use an anonymous type.
使用匿名类型。
Eg
例如
group x by new { x.Column1, x.Column2 }
回答by Sreedhar
Ok got this as:
好的得到这个:
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();
回答by Mo0gles
Procedural sample
程序样本
.GroupBy(x => new { x.Column1, x.Column2 })
回答by Chris Smith
Though this question is asking about group by class properties, if you want to group by multiple columns against a ADO object (like a DataTable), you have to assign your "new" items to variables:
尽管这个问题是关于按类属性分组的,但如果您想针对 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);
回答by Jay Bienvenu
You can also use a Tuple<> for a strongly-typed grouping.
您还可以使用 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),
}
回答by Milan
For Group By Multiple Columns, Try this instead...
对于按多列分组,试试这个...
GroupBy(x=> new { x.Column1, x.Column2 }, (key, group) => new
{
Key1 = key.Column1,
Key2 = key.Column2,
Result = group.ToList()
});
Same way you can add Column3, Column4 etc.
以同样的方式您可以添加 Column3、Column4 等。
回答by Arindam
var Results= query.GroupBy(f => new { /* add members here */ });
回答by Arindam
Since C# 7 you can also use value tuples:
从 C# 7 开始,您还可以使用值元组:
group x by (x.Column1, x.Column2)
or
或者
.GroupBy(x => (x.Column1, x.Column2))
回答by Kai Hartmann
.GroupBy(x => x.Column1 + " " + x.Column2)
回答by John
group x by new { x.Col, x.Col}
按 new { x.Col, x.Col} 分组 x