Come compilare una DataTable con un Elenco (Of t) o convertire un Elenco (Of t) in un DataTable?
-
05-07-2019 - |
Domanda
Ho letto molti post su questo argomento; tra questi e più recentemente .NET - Converti raccolta generica in tabella dati . Sfortunatamente, tutto inutilmente.
Ho una raccolta generica di strutture:
Private Structure MyStruct
Dim sState as String
Dim lValue as Long
Dim iLayer as Integer
End Structure
Dim LOStates As New List(Of MyStruct)
Devo compilare una DataTable con questo elenco di strutture ma non ho idea di come procedere. Sto usando vb.net in Visual Studio 2008.
Eventuali approfondimenti saranno molto apprezzati
Soluzione
Il codice collegato presuppone che i membri siano dichiarati come proprietà. Non hai dichiarato le proprietà. Puoi farlo funzionare 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
Altri suggerimenti
Ho lo stesso problema di @SamSelikoff, spostato su 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
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow