在VB.NET中使用LINQ将DataTable转换为Dictionary

时间:2014-06-20 10:51:56

标签: vb.net linq datatable

我有一个DataTable,它使用这个SQL从SQL表中提取结果:

SELECT firstName,lastName,companyName,address1,countryCode FROM dbo.users

我想将此DataTable转换为Dictionary-esque结构,其中上面每个字段的键是列名,值是该列的每个DataRow的值。我对如何在C#中进行操作有一个模糊的想法,但VB.NET LINQ语法完全不同,所以我很难弄清楚如何做到这一点。

结构(在JSON中可视化)将是这样的:

[
    {
        "firstName": "Adam",
        "lastName": "Smith",
        "address1": "123 Old St",
        "companyName": "Fake Company",
        "countryCode": "us"
    },
    {
        "firstName": "Paul",
        "lastName": "Jones",
        "address1": "474 Old St",
        "companyName": "Fake Company",
        "countryCode": "gb"
    }
]

1 个答案:

答案 0 :(得分:3)

Dictionary(Of String, String)将与你所获得的字典一样:

Dim result As IEnumerable(Of Dictionary(Of String, String)) =
    From r As DataRow In myDataTable.AsEnumerable()
    Select New Dictionary(Of String, String) From {
        { "firstName", r.Field(Of String)("firstName") },
        { "lastName", r.Field(Of String)("lastName") },
        { "address1", r.Field(Of String)("address1") },
        { "companyName", r.Field(Of String)("companyName") },
        { "countryCode", r.Field(Of String)("countryCode") }
    }

您也可以使用匿名类型:

Dim result2 =
    From r In myDataTable.AsEnumerable()
    Select New With {
        .firstName = r.Field(Of String)("firstName"),
        .lastName = r.Field(Of String)("lastName"),
        .address1 = r.Field(Of String)("address1"),
        .companyName = r.Field(Of String)("companyName"),
        .countryCode = r.Field(Of String)("countryCode")
    }

或者,正如评论中所建议的那样,您可以创建一个类并返回:

Public Class User
    Public Property firstName As String
    Public Property lastName As String
    Public Property address1 As String
    Public Property companyName As String
    Public Property countryCode As String
End Class

Dim result3 =
    From r In myDataTable.AsEnumerable()
    Select New User With {
        .firstName = r.Field(Of String)("firstName"),
        .lastName = r.Field(Of String)("lastName"),
        .address1 = r.Field(Of String)("address1"),
        .companyName = r.Field(Of String)("companyName"),
        .countryCode = r.Field(Of String)("countryCode")
    }