Convertir Lista a DataTable Visual Basic .NET

La siguiente función permite convertir cualquier clase heredada de IList en un DataTable.

Referencia

Imports System.Reflection
Imports System.ComponentModel

Código

    Public Shared Function ConvertToDataTable(Of T)(ByVal list As IList(Of T)) As DataTable
        Dim td As New DataTable
        Dim entityType As Type = GetType(T)
        Dim properties As PropertyDescriptorCollection = TypeDescriptor.GetProperties(entityType)

        For Each prop As PropertyDescriptor In properties
            td.Columns.Add(prop.Name)
        Next

        For Each item As T In list
            Dim row As DataRow = td.NewRow()

            For Each prop As PropertyDescriptor In properties
                row(prop.Name) = prop.GetValue(item)
            Next

            td.Rows.Add(row)
        Next

        Return td
    End Function

Esperamos sea de su utilidad,

Saludos

También te podría gustar...

2 Respuestas

  1. Dany Aracena dice:

    Muchas, Muchas Gracias

  2. Mario Macias dice:

    GRACIAS muchisimas

Deja una respuesta

Tu dirección de correo electrónico no será publicada.