How to convert DataSet into Dictionary in vb.net?
My WCF service function return type is 开发者_C百科Dictionary(Of String, String). So I have to convert my Dataset to Dictionary.
Here is my dataset example.
Account AccountNames
abc abc1
abc abc2
abc abc3
xyz xyz1
xyz xyz2
xyz xyz3
xyz xyz4
pqr pqr1
pqr pqr2
pqr pqr3
pqr pqr4
pqr pqr5
pqr pqr6
Using LINQ or without LINQ, How can I convert Dataset To Dictionary(Of String, String)
Regards, RN
Assuming the 2nd column are the keys you can do this:
Dim ds As DataSet = someValueHere
Dim dc As New Dictionary(Of String, String)
For Each r As DataRow In ds.Tables(0).Rows
dc.Add(r.Item(1).ToString(), r.Item(0).ToString())
Next
I don't know if there will be a shortcut for linq. Note: dictionary cannot contain duplicate keys, so if the 1st column corresponds the key and the 2nd column for the values, it is not possible.
Here's a few options using LINQ.
The most direct "one-liner" is:
Dim dictionary =
ds.Tables(0).Rows.OfType(Of DataRow)() _
.ToDictionary(Function (dr) dr.Field(Of String)(0), _
Function (dr) dr.Field(Of String)(1))
I think the VB.NET lamdba syntax is a little ugly so I like to pull them out like this:
Dim fk As Func(Of DataRow, String) = Function (dr) dr.Field(Of String)(0)
Dim fv As Func(Of DataRow, String) = Function (dr) dr.Field(Of String)(1)
Dim dictionary = ds.Tables(0).Rows.OfType(Of DataRow)().ToDictionary(fk, fv)
That might even be too ugly, so this is an option:
Dim fn as Func(Of Integer, Func(Of DataRow, String)) = _
Function (n) _
Function (dr) _
dr.Field(Of String)(n)
Dim dictionary = ds.Tables(0).Rows.OfType(Of DataRow)().ToDictionary(fn(0), fn(1))
Or even by column name:
Dim fs as Func(Of String, Func(Of DataRow, String)) = _
Function (s) _
Function (dr) _
dr.Field(Of String)(s)
Dim dictionary =
ds.Tables(0).Rows.OfType(Of DataRow)() _
.ToDictionary(fs("AccountName"), fs("Account"))
I hope these help.
Here's an example with LINQ, using the same assumption that jerjer's answer had (that the 2nd column are the keys):
Dim dict As Dictionary(Of string, string) = (From a In ds.Tables(0).AsEnumerable()
Select New With
{
.Key = a.Field(Of String)("AccountName"),
.Val = a.Field(Of String)("Account")
}).AsEnumerable().ToDictionary(Function(k) k.Key, Function(v) v.Val)
The syntax may be a bit off, as I don't do VB.NET that much, but that should give you the general idea.
精彩评论