我这里有这个代码:
Dim result As IEnumerable(Of Object())
Dim dt As New DataTable
Dim indexes As New List(Of Integer)
Dim groupedindexes As New List(Of Integer)
Dim datarows As New List(Of DataRow)
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
dt.Columns.Add("f1", Type.GetType("System.Char"))
dt.Columns.Add("f2", Type.GetType("System.Char"))
dt.Columns.Add("f3", Type.GetType("System.Char"))
dt.Columns.Add("f4", Type.GetType("System.Int32"))
For i = 0 To 100
dt.Rows.Add("a", "b", "c", i * 2)
Next
indexes.Add(0)
indexes.Add(1)
indexes.Add(2)
indexes.Add(3)
groupedindexes.Add(0)
groupedindexes.Add(1)
groupedindexes.Add(2)
For i = 0 To dt.Rows.Count - 1
datarows.Add(dt.Rows(i))
Next
result = datarows.Select(Function(row) indexes.Select(Function(index) row(index)).ToArray)
'select sum(f4), f1, f2, f3 from t1 group by f1, f2, f3
Dim test = result.GroupBy(Function(Key) groupedindexes.Select(Function(groupedindex) Key(groupedindex)).ToArray,
Function(Result) indexes.Select(Function(index) Result(index)).ToArray)
End Sub
我正在按方法/功能尝试该组。通过上面的代码,我设法得到一个测试结果,按f1,f2和f3分组。现在,我想实现sum函数,就像SQL查询所说:
select sum(f4), f1, f2, f3 from t1 group by f1, f2, f3
我试过这样的事情:
Dim test = result.GroupBy(Function(Key) groupedindexes.Select(Function(groupedindex) Key(groupedindex)).ToArray,
Function(Result) indexes.Select(Function(index) Result(index)).ToArray).Select(
Function(groupedrow) New With
{Key .sum_of_f4 = groupedrow.Sum(Function(row) Convert.ToInt32(row(3))),
Key .f1 = groupedrow.Key(0),
Key .f2 = groupedrow.Key(1),
Key .f3 = groupedrow.Key(2)})
但是f4没有求和,我得到了所有101行。
如何更正我的代码以获得所需的结果?
答案 0 :(得分:0)
我不太关注你试图用“test”表达式做什么,但是如果要实现提到的SQL,我想这样的简单查询应该这样做:
Dim Result = (
From i in dt.Rows
Group By f1 = i("f1"), f2 = i("f2"), f3 = i("f3")
Into f4 = Sum(i("f4"))
).ToList
更新:方法语法
Dim Data = datarows.GroupBy(Function(x) New With {Key .f1 = x("f1"), Key .f2 = x("f2"), Key .f3 = x("f3")}).Select(Function(x) New With {.f1 = x(0)("f1"), .f2 = x(0)("f2"), .f3 = x(0)("f3"), .f4 = x.Sum(Function(i) i(3))}).ToList