按多列分组
我如何在 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
How can I do GroupBy multiple columns in LINQ
Something similar to this in SQL:
SELECT * FROM <TableName> GROUP BY <Column1>,<Column2>
How can I convert this to 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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(15)
使用匿名类型。
例如
Use an anonymous type.
Eg
程序示例:
Procedural sample:
好的,得到这个:
Ok got this as:
对于按多列分组,请尝试此操作...
您可以使用相同的方式添加 Column3、Column4 等。
For Group By Multiple Columns, Try this instead...
Same way you can add Column3, Column4 etc.
从 C# 7 开始,您还可以使用值元组:
或
Since C# 7 you can also use value tuples:
or
使用
元组
和推断元组元素名称
的C# 7.1或更高版本(目前它仅适用于linq to objects
并且它当需要表达式树时不支持,例如someIQueryable.GroupBy(...)
。 ">Github 问题):C# 3 或更高版本使用
匿名类型
:C# 7.1 or greater using
Tuples
andInferred tuple element names
(currently it works only withlinq to objects
and it is not supported when expression trees are required e.g.someIQueryable.GroupBy(...)
. Github issue):C# 3 or greater using
anonymous types
:您还可以使用 Tuple<> 对于强类型分组。
You can also use a Tuple<> for a strongly-typed grouping.
虽然这个问题询问的是按类属性分组,但如果您想针对 ADO 对象(如 DataTable)按多个列进行分组,则必须将“新”项分配给变量:
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:
需要注意的是,您需要为 Lambda 表达式发送一个对象,并且不能使用类的实例。
示例:
这将编译,但将生成每个周期一个密钥。
如果您不想命名关键属性然后检索它们,您可以这样做。 这将正确地
GroupBy
并为您提供关键属性。A thing to note is that you need to send in an object for Lambda expressions and can't use an instance for a class.
Example:
This will compile but will generate one key per cycle.
If you wan't to name the key properties and then retreive them you can do it like this instead. This will
GroupBy
correctly and give you the key properties.通过 new { x.Col, x.Col} 对 x 进行分组
group x by new { x.Col, x.Col}
.GroupBy(x => (x.MaterialID, x.ProductID))
.GroupBy(x => (x.MaterialID, x.ProductID))
对于VB和匿名/lambda:
For VB and anonymous/lambda:
其他答案适用于固定\静态列,您知道在编码时要对哪些内容进行分组。 但是,如果您在程序运行之前不知道要按哪些列或多少列进行分组,您可以执行以下操作:
示例使用:
Other answers are good for fixed\static columns, where you know what to group on when you code. But if you do not know which or how many columns to group by until the program is run, you could do something like:
Example use: