为什么以下group by子句不起作用? 最初的问题是我如何在带有DataTable的vb代码(dot.net v4.0)中的LINQ中执行组并对组进行求和?这是样本,但它没有产生所需的输出。 它返回2行而不是一行。
Dim table As New DataTable()
table.Columns.Add("GroupName", GetType(String))
table.Columns.Add("ProductName", GetType(String))
table.Columns.Add("QTY", GetType(Integer))
table.Rows.Add("a", "b", 1)
table.Rows.Add("a", "b", 1)
Dim testQuery =
(From e In table
Group e By Key = New With {
.GroupName = e("GroupName"),
.ProductName = e("ProductName")
} Into Group
Select New With {
.ProductName = Key.ProductName,
.QTY = Group.Sum(Function(x) Convert.ToInt32(x("QTY"))),
.GroupName = Key.GroupName
})
答案 0 :(得分:6)
在VB.NET中,按组合键分组的语法是以逗号分隔的键,而不是匿名类型:
(From e In table
Group e By
GroupName = e("GroupName"),
ProductName = e("ProductName")
Into Group
Select New With {
.ProductName = ProductName,
.QTY = Group.Sum(Function(x) Convert.ToInt32(x("QTY"))),
.GroupName = GroupName
})
使用您的语法,它只使用匿名对象上的默认相等比较器,它不会比较字段。
答案 1 :(得分:0)
Dim testQuery =
(From e In table
Group e By Key = New With {.GroupName = e("GroupName")}.GroupName,
New With {.ProductName = e("ProductName")}.ProductName Into Group
Select New With {
.ProductName = ProductName,
.QTY = Group.Sum(Function(x) Convert.ToInt32(x("QTY"))),
.GroupName = Key.ToString
})