Vor kurzem musste ich in einer Anwendung eine LinQtoSQL-Abfrage einem DataTable zuweisen.
Im Web fand ich auf einer chinesischen Seite hierfür folgende nützliche Funktion:(http://blog.csdn.net/gdjlc/archive/2010/07/06/5714918.aspx)
Für' Archiv hier in C#
public DataTable ConvertToDataTable<T>(IEnumerable<T> varlist)
{
DataTable dtReturn = new DataTable();
// column names
PropertyInfo[] oProps = null;
if (varlist == null) return dtReturn;
foreach (T rec in varlist)
{
// Use reflection to get property names, to create table, Only first time, others will follow
if (oProps == null)
{
oProps = ((Type)rec.GetType()).GetProperties();
foreach (PropertyInfo pi in oProps)
{
Type colType = pi.PropertyType;
if ((colType.IsGenericType) && (colType.GetGenericTypeDefinition() == typeof(Nullable<>)))
{
colType = colType.GetGenericArguments()[0];
}
dtReturn.Columns.Add(new DataColumn(pi.Name, colType));
}
}
DataRow dr = dtReturn.NewRow();
foreach (PropertyInfo pi in oProps)
{
dr[pi.Name] = pi.GetValue(rec, null) == null ? DBNull.Value : pi.GetValue(rec, null);
}
dtReturn.Rows.Add(dr);
}
return dtReturn;
}
und in VB.NET:
Public Function ConvertToDataTable(Of T)(ByVal varlist As IEnumerable(Of T)) As DataTable
Dim dtReturn As New DataTable()
' column names
Dim oProps As PropertyInfo() = Nothing
If varlist Is Nothing Then
Return dtReturn
End If
For Each rec As T In varlist
' Use reflection to get property names, to create table
If oProps Is Nothing Then
oProps = DirectCast(rec.[GetType](), Type).GetProperties()
For Each pi As PropertyInfo In oProps
Dim colType As Type = pi.PropertyType
If (colType.IsGenericType)
AndAlso (colType.GetGenericTypeDefinition().ToString()
= GetType(Nullable(Of )).ToString())
Then
colType = colType.GetGenericArguments()(0)
End If
dtReturn.Columns.Add(New DataColumn(pi.Name, colType))
Next
End If
Dim dr As DataRow = dtReturn.NewRow()
For Each pi As PropertyInfo In oProps
dr(pi.Name) = If(pi.GetValue(rec, Nothing) Is Nothing, DBNull.Value, pi.GetValue(rec, Nothing))
Next
dtReturn.Rows.Add(dr)
Next
Return dtReturn
End Function