This question concerns generics and types, as well as data.
The following snippet is around the network here and there and creates data based on the generic type:
public static DataTable ListToDataTable<T>(List<T> list)
{
DataTable dt = new DataTable();
foreach (PropertyInfo info in typeof(T).GetProperties())
{
dt.Columns.Add(new DataColumn(info.Name, info.PropertyType));
}
foreach (T t in list)
{
DataRow row = dt.NewRow();
foreach (PropertyInfo info in typeof(T).GetProperties())
{
row[info.Name] = info.GetValue(t, null);
}
dt.Rows.Add(row);
}
return dt;
}
I use the excellent FileHelpers library to import batches of records into SQL Server. To use SqlBulkCopy, I need a data type with columns from a given type. Filehelpers can read in a .cs file at runtime and create a type on it. eg:
System.Type userType = null;
userType = ClassBuilder.ClassFromSourceFile("myclassfile.cs");
I would like to change the method above, so it just creates columns for me when passing the type (e.g. 'userType'). those. the signature of the method will be something like this:
public static DataTable TypeToDataTable<T>(<T> myType)
and returns an empty dataset with columns, ready to add userType rows to it.
I tried various methods - any ideas?