Linq查询在VB.net中分组几列

时间:2015-03-04 17:55:47

标签: vb.net linq

好的,我有下表

Dt.Columns.Add("A1")
Dt.Columns.Add("A2")
Dt.Columns.Add("A3")
Dt.Columns.Add("A4")
Dt.Rows.Add("A", "1", "11", "111")
Dt.Rows.Add("B", "1", "11", "111")
Dt.Rows.Add("C", "1", "12", "121")
Dt.Rows.Add("D", "1", "12")
Dt.Rows.Add("E", "2", "21", "211")
Dt.Rows.Add("F", "2", "21")
Dt.Rows.Add("G", "3")
Dt.Rows.Add("H", "3")
Dt.Rows.Add("I", "3", "31")

我有以下Linq查询

    Dim Query = From Row In Dt.AsEnumerable()
                Group Key = Row(1), Key2 = Row(2), Key3 = Row(3)
                By Key = Row(1)
                Into Test = Group

这给了我以下结果

    "1", "11", "111"
    "1", "11", "111"
    "1", "12", "121"
    "1", "12"

但我想让查询给我这个

"1", "11", "111"
"1", "12", "121"
"1", "12", null
"2", "21", "211"
"2", "21", null
"3", null, null
"3", "31", null

简单来说,我希望查询按最后3列分组并输出这些列的分组。在Sql中它将是:

Select A2,A3,A4
From Dt
Group by A2,A3,A4

我一直在与Linq战斗了几个小时,但无济于事我能够得到我想要的东西。

1 个答案:

答案 0 :(得分:0)

尝试,

Dim Query = From Row In Dt.Rows
            Group Key = Row(1), Key2 = Row(2), Key3 = Row(3)
            By Key = Row(1), Key2 = Row(2)
            Into Test = Group

<强>更新

考虑一下你可能需要

By Key = Row(1), Key2 = Row(2), Key3 = Row(3)