1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
| Imports System.Data
Imports System.Collections.Generic
Imports System.Reflection
Imports System.Runtime.CompilerServices
Public Module Extensions
<Extension>
Public Shared Function ToDataTable(Of T)(source As IEnumerable(Of T)) As DataTable
Dim table As New DataTable()
Dim properties As PropertyInfo() = GetType(T).GetProperties()
' On crée les colonnes pour chaque propriété
For Each p In properties
table.Columns.Add(p.Name, p.PropertyType)
Next
' On crée les lignes pour chaque élément de la séquence
For Each item In source
Dim row As DataRow = table.NewRow()
' On copie les valeurs de chaque colonne
For Each p In properties
row(p.Name) = p.GetValue(item, Nothing)
Next
table.Rows.Add(row)
Next
Return table
End Function
End Class |