¿Cómo llenar una tabla de datos con una lista (Of t) o convertir una lista (de t) en una tabla de datos?

StackOverflow https://stackoverflow.com/questions/1805626

Pregunta

He leído muchas publicaciones sobre este tema; entre ellos y más recientemente, .NET - Convierta la colección genérica en una tabla de datos . Desafortunadamente, todo fue en vano.

Tengo una colección genérica de estructuras:

Private Structure MyStruct
Dim sState as String
Dim lValue as Long
Dim iLayer as Integer
End Structure

Dim LOStates As New List(Of MyStruct)

Necesito completar un DataTable con esta lista de estructuras, pero no tengo idea de cómo hacerlo. Estoy usando vb.net en Visual Studio 2008.

Cualquier idea será muy apreciada

¿Fue útil?

Solución

El código que vinculó asume que los miembros se declaran como propiedades. No has declarado propiedades. Puede hacerlo funcionar con Reflection:

Imports System.Reflection
...

      Public Shared Function ConvertToDataTable(Of T)(ByVal list As IList(Of T)) As DataTable
        Dim table As New DataTable()
        Dim fields() As FieldInfo = GetType(T).GetFields()
        For Each field As FieldInfo In fields
          table.Columns.Add(field.Name, field.FieldType)
        Next
        For Each item As T In list
          Dim row As DataRow = table.NewRow()
          For Each field As FieldInfo In fields
            row(field.Name) = field.GetValue(item)
          Next
          table.Rows.Add(row)
        Next
        Return table
      End Function

Otros consejos

Tengo el mismo problema que @SamSelikoff, movido a GetProperties:

Public Shared Function ConvertToDataTable(Of t)(
                                                  ByVal list As IList(Of t)
                                               ) As DataTable
    Dim table As New DataTable()
    If Not list.Any Then
        'don't know schema ....
        Return table
    End If
    Dim fields() = list.First.GetType.GetProperties
    For Each field In fields
        table.Columns.Add(field.Name, field.PropertyType)
    Next
    For Each item In list
        Dim row As DataRow = table.NewRow()
        For Each field In fields
            dim p = item.GetType.GetProperty(field.Name)
            row(field.Name) = p.GetValue(item, Nothing)
        Next
        table.Rows.Add(row)
    Next
    Return table
End Function
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top