public static DataSet ToDataSet<TSource>(this IList<TSource> list)
{
Type elementType = typeof(TSource);
DataSet ds = new DataSet();
DataTable dt = new DataTable();
ds.Tables.Add(dt);
foreach (var pi in elementType.GetProperties())
{
Type colType = Nullable.GetUnderlyingType(pi.PropertyType) ?? pi.PropertyType;
dt.Columns.Add(pi.Name, colType);
}
foreach (TSource item in list)
{
DataRow row = dt.NewRow();
foreach (var pi in elementType.GetProperties())
{
row[pi.Name] = pi.GetValue(item, null) ?? DBNull.Value;
}
dt.Rows.Add(row);
}
return ds;
}