Pergunta

Eu li muitos posts sobre este tema; entre eles e, mais recentemente .NET - Converter coleção genérica a Tabela de Dados . Infelizmente, todos sem sucesso.

Eu tenho uma coleção genérica de estruturas:

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

Dim LOStates As New List(Of MyStruct)

Eu preciso preencher uma DataTable com esta lista de estruturas, mas não têm idéia de como ir sobre fazer isto. Eu estou usando vb.net no Visual Studio 2008.

Qualquer insights será muito apreciada

Foi útil?

Solução

O código é ligada assume os membros são declarados como propriedades. Você não declarou propriedades. Você pode fazê-lo funcionar com reflexão:

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

Outras dicas

Eu tenho mesmo problema que @SamSelikoff, mudou-se para 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 em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top