Converts a Generic List to a DataTable.
// Method: 1
// http://www.extensionmethod.net/csharp/datatable-c-list/list-to-datatable
//
// Converts a List to a DataTable.
public static DataTable ToDataTable<T>(this IList<T> data)
{
PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(typeof(T));
DataTable table = new DataTable();
foreach (PropertyDescriptor prop in properties)
{
table.Columns.Add(prop.Name, Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType);
}
foreach (T item in data)
{
DataRow row = table.NewRow();
foreach (PropertyDescriptor prop in properties)
{
row[prop.Name] = prop.GetValue(item) ?? DBNull.Value;
}
table.Rows.Add(row);
}
return table;
}
//
// Example:
List<string> myList = New String[]{"a","b","c","d"}.ToList();
DataTable dt = new DataTable();
dt = myList.ToDataTable();
/// -------------------------------------------------------------------------
// Method: 2
// http://www.extensionmethod.net/csharp/ienumerable-t/todatatable
public static DataTable ToDataTable<T>(this IEnumerable<T> varlist)
{
DataTable dtReturn = new DataTable();
if (varlist == null) return dtReturn;
// column names
PropertyInfo[] oProps = null;
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;
}
//
// Example: It will result an IQueryable (IEnumerable)
var result = from c in db.customer
where c.id = 26
select c;
DataTable dtResults = new DataTable();
dtResults = result.ToDataTable();