Re: IEnumerable to DataTable
Code updated to include support for nullable data types.
Re: IEnumerable to DataTable
Nice.
I have done something similar for a list(of t) a couple of years ago. Might worth putting it here:
Code:
Imports System.ComponentModel
Imports System.Reflection
Public Module BulkExtentions
<System.Runtime.CompilerServices.Extension()>
Public Function ToDataTable(Of T)(data As IEnumerable(Of T)) As DataTable
Dim properties As PropertyDescriptorCollection = TypeDescriptor.GetProperties(GetType(T))
Dim table = New DataTable()
For Each prop As PropertyDescriptor In properties
table.Columns.Add(prop.Name, If(Nullable.GetUnderlyingType(prop.PropertyType), prop.PropertyType))
Next
For Each item As T In data
Dim row As DataRow = table.NewRow()
For Each prop As PropertyDescriptor In properties
row(prop.Name) = If(prop.GetValue(item), DBNull.Value)
Next
table.Rows.Add(row)
Next
Return table
End Function
<System.Runtime.CompilerServices.Extension()>
Public Function ConvertDataTableToList(Of T)(ByVal dt As DataTable) As List(Of T)
Dim data As List(Of T) = New List(Of T)()
For Each row As DataRow In dt.Rows
Dim item As T = GetItem(Of T)(row)
data.Add(item)
Next
Return data
End Function
Private Function GetItem(Of T)(ByVal dr As DataRow) As T
Dim temp As Type = GetType(T)
Dim obj As T = Activator.CreateInstance(Of T)()
For Each column As DataColumn In dr.Table.Columns
For Each pro As PropertyInfo In temp.GetProperties()
If pro.Name.ToLower() = column.ColumnName.ToLower() Then
pro.SetValue(obj, dr(column.ColumnName), Nothing)
Else
Continue For
End If
Next
Next
Return obj
End Function
End Module
Public NotInheritable Class IEnumerableExtensions
Private Sub New()
End Sub
End Class