List<T> To DataTable
public DataTable ListToDataTable<T>(List<T> list) where T : class
{
DataTable dt = new DataTable();
foreach (PropertyInfo info in typeof(T).GetProperties())
{
dt.Columns.Add(new DataColumn(info.Name, info.PropertyType));
}
foreach (var item in list)
{
DataRow row = dt.NewRow();
foreach (PropertyInfo info in typeof(T).GetProperties())
{
//todo: 如果T的属性有List<>类型的,这里不会得到预期的结果,需要进一步处理
row[info.Name] = info.GetValue(item, null);
}
dt.Rows.Add(row);
}
return dt;
}

浙公网安备 33010602011771号