public static DataTable ToDataTable<T>(IList<T> list)
{
Type entityType = typeof(T);
DataTable table = new DataTable(entityType.Name);
PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(entityType);//获取实体类属性
foreach (PropertyDescriptor prop in properties)
{
table.Columns.Add(prop.Name, prop.PropertyType);//根据属性添加DataTable的列
}
foreach (T item in list)//添加list的数据到datatable
{
DataRow row = table.NewRow();
foreach (PropertyDescriptor prop in properties)
row[prop.Name] = prop.GetValue(item);
table.Rows.Add(row);
}
return table;
}
c# list转datatable
最新推荐文章于 2023-11-03 11:27:22 发布