Below is a class that contains a method that can create a DataTable object form Linq Query Results. I find the LINQToDataTable method really handy when I am creating Crystal reports. Crystal Reports love to report on DataTables.
The Imports are essential to the LINQToDataTable method in the LinqUtilities class.
Imports System.Data
Imports System.Linq
Imports System.Reflection
Public Class LinqUtilities
Friend Shared Function LINQToDataTable(Of T)(ByVal iEnumerableList As IEnumerable(Of T)) As DataTable
Dim newDataTable As New DataTable()
Dim thePropertyInfo As PropertyInfo() = Nothing
If iEnumerableList Is Nothing Then
Return newDataTable
End If
For Each item As T In iEnumerableList
If thePropertyInfo Is Nothing Then
thePropertyInfo = (DirectCast(item.[GetType](), Type)).GetProperties()
For Each propInfo As PropertyInfo In thePropertyInfo
Dim columnDataType As Type = propInfo.PropertyType
If (columnDataType.IsGenericType) AndAlso (columnDataType.GetGenericTypeDefinition() Is GetType(Nullable(Of ))) Then
columnDataType = columnDataType.GetGenericArguments()(0)
End If
newDataTable.Columns.Add(New DataColumn(propInfo.Name, columnDataType))
Next
End If
Dim dr As DataRow = newDataTable.NewRow()
For Each pi As PropertyInfo In thePropertyInfo
dr(pi.Name) = If(pi.GetValue(item, Nothing) Is Nothing, DBNull.Value, pi.GetValue(item, Nothing))
Next
newDataTable.Rows.Add(dr)
Next
Return newDataTable
End Function
End Class
Below is example code that uses Linq to query for all the buttons on a Windows Forms form and calls the LINQToDataTable method to put the query results into a DataTable.
Dim newDataTable As DataTable = _
LinqUtilities.LINQToDataTable(From btn In Me.Controls _
Where TypeOf (btn) Is Button Select btn)
Mike McIntyre's .Net Journal
getdotnetcode.com