在 VB.NET 中使用 LINQ 将 DataTable 转换为字典
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24325606/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Converting DataTable to Dictionary using LINQ in VB.NET
提问by adaam
I have a DataTable which pulls out results from a SQL table using this SQL:
我有一个 DataTable,它使用此 SQL 从 SQL 表中提取结果:
SELECT firstName,lastName,companyName,address1,countryCode FROM dbo.users
I would like to convert this DataTable to a Dictionary-esque structure with the key for each field above being the column name and the value being the value for each DataRow for that column. I have a vague idea of how to do it in C# but the VB.NET LINQ syntax is completely different so I'm struggling to figure out how to do this..
我想将此 DataTable 转换为字典式结构,上面每个字段的键是列名,值是该列的每个 DataRow 的值。我对如何在 C# 中做到这一点有一个模糊的想法,但 VB.NET LINQ 语法完全不同,所以我正在努力弄清楚如何做到这一点..
Structure (visualized in JSON) would be something like this:
结构(在 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"
}
]
回答by Mark
A Dictionary(Of String, String)would be about as Dictionary-esque as you could get:
ADictionary(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") }
}
You could also use an anonymous type:
您还可以使用匿名类型:
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")
}
Or, as suggested in the comments, you could create a class and return that:
或者,正如评论中所建议的,您可以创建一个类并返回:
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")
}

