ToDictionary

Imports System.Runtime.CompilerServices

Public Module DataTableExtensions

    ''' <summary>
    ''' Converts Dictionary to DataTable
    ''' </summary>
    ''' <typeparam name="Tkey"></typeparam>
    ''' <typeparam name="TVal"></typeparam>
    ''' <param name="dict"></param>
    ''' <returns></returns>
    <Extension()>
    Public Function FromDictionary(Of Tkey, TVal)(ByRef dict As Dictionary(Of Tkey, TVal)) As DataTable
        Dim dt As New DataTable("Dictionary")

        dt.Columns.Add(New DataColumn("Key", GetType(Tkey)))
        dt.Columns.Add(New DataColumn("Value", GetType(TVal)))

        For Each dictentry In dict
            Dim newrow As DataRow = dt.Rows.Add()
            newrow.Item("Key") = dictentry.Key
            newrow.Item("Value") = dictentry.Value
        Next
        Return dt
    End Function


    ''' <summary>
    ''' Converts DataTable to Dictionary
    ''' </summary>
    ''' <typeparam name="Tkey"></typeparam>
    ''' <typeparam name="TVal"></typeparam>
    ''' <param name="dt"></param>
    ''' <returns></returns>
    <Extension()>
    Public Function ToDictionary(Of Tkey, TVal)(ByRef dt As DataTable) As Dictionary(Of Tkey, TVal)
        Dim dict As New Dictionary(Of Tkey, TVal)
        For Each row As DataRow In dt.Rows
            dict.Add(row.Field(Of Tkey)("Key"), row.Field(Of TVal)("Value"))
        Next
        Return dict
    End Function

End Module
Example:
Dim testdict As New Dictionary(Of String, Int16)
testdict.Add("Gollum", 123)
testdict.Add("ALF", 15)
testdict.Add("Gandalf", 66)

Dim y As DataTable = FromDictionary(Of String, Int16)(testdict)

Dim yy As Dictionary(Of String, Int16)= ToDictionary(Of String, Int16)(y)

Description

Converts Dictionary to DataTable and DataTable to Dictionary

Details

Double click on the code to select all.

 

;