public static DataSet ToDataSet<T>(this IList<T> list)
{
if (list != null)
{
Type elementType = typeof(T);
var ds = new DataSet();
var t = new DataTable();
ds.Tables.Add(t);
elementType.GetProperties().ToList().ForEach(propInfo => t.Columns.Add(propInfo.Name, Nullable.GetUnderlyingType(propInfo.PropertyType) ?? propInfo.PropertyType));
foreach (T item in list)
{
var row = t.NewRow();
elementType.GetProperties().ToList().ForEach(propInfo => row[propInfo.Name] = propInfo.GetValue(item, null) ?? DBNull.Value);
t.Rows.Add(row);
}
return ds;
}
else
{
return null;
}
}
转载于:https://my.oschina.net/guanxinsui/blog/918993