ExtensionMethod.NET Home of 818 C#, Visual Basic, F# and Javascript extension methods

ToDatatable

Creates a DataTable representation of a Dictionary

Source

<System.Runtime.CompilerServices.Extension()> _
Public Function ToDatatable(ByVal sender As IDictionary) As DataTable

    Dim Types() As Type = sender.GetType().GetGenericArguments()
    Dim keyType As Type = Types(0)
    Dim valueType As Type = Types(1)

    Dim dt As New DataTable With {.TableName = "MyDict"}

    With dt.Columns
        .AddRange(New DataColumn() _
           { _
              New DataColumn("Key", System.Type.GetType(keyType.ToString)), _
              New DataColumn("Value", System.Type.GetType(valueType.ToString)) _
           } _
        )
    End With

    For Each de As DictionaryEntry In sender
        dt.Rows.Add(New Object() {de.Key, de.Value})
    Next

    Return dt

End Function

Example

Private Sub DataTableToDictionary1()
    Dim Demo1 As New Dictionary(Of Integer, String)

    For x As Integer = 65 To 75
        Demo1.Add(x, ChrW(x))
    Next

    Dim dtDemo1 = Demo1.ToDatatable
    Console.WriteLine(dtDemo1.Rows.Count)
    For Each Row As DataRow In dtDemo1.Rows
        Console.WriteLine("{0}={1}", Row("key"), Row("value"))
    Next

End Sub

Author: Kevin S Gallagher

Submitted on: 2 okt 2010

Language: VB

Type: System.Collections.Generic.IDictionary

Views: 2981