/// <summary>
/// 将List转换为DataTable
/// </summary>
/// <param name="list">请求数据</param>
/// <returns></returns>
public static DataTable ListToDataTable<T>(List<T> list)
{
//创建一个名为"tableName"的空表
DataTable dt = new DataTable("tableName");
//创建传入对象名称的列
foreach (var item in list.FirstOrDefault().GetType().GetProperties())
{
dt.Columns.Add(item.Name);
}
//循环存储
foreach (var item in list)
{
//新加行
DataRow value = dt.NewRow();
//根据DataTable中的值,进行对应的赋值
foreach (DataColumn dtColumn in dt.Columns)
{
int i = dt.Columns.IndexOf(dtColumn);
//基元元素,直接复制,对象类型等,进行序列化
if (value.GetType().IsPrimitive)
{
value[i] = item.GetType().GetProperty(dtColumn.ColumnName).GetValue(item);
}
else
{
value[i] = JsonConvert.SerializeObject(item.GetType().GetProperty(dtColumn.ColumnName).GetValue(item));
}
}
dt.Rows.Add(value);
}
return dt;
}
public static DataTable ListToDataTable<T>(List<T> list)
{
System.Data.DataTable result = new System.Data.DataTable();
if (list.Count > 0)
{
PropertyInfo[] propertys = list[0].GetType().GetProperties();
foreach (PropertyInfo pi in propertys)
{
//获取类型
Type colType = pi.PropertyType;
//当类型为Nullable<>时
if ((colType.IsGenericType) && (colType.GetGenericTypeDefinition() == typeof(Nullable<>)))
{
colType = colType.GetGenericArguments()[0];
}
result.Columns.Add(pi.Name, colType);
}
for (int i = 0; i < list.Count; i++)
{
ArrayList tempList = new ArrayList();
foreach (PropertyInfo pi in propertys)
{
object obj = pi.GetValue(list[i], null);
tempList.Add(obj);
}
object[] array = tempList.ToArray();
result.LoadDataRow(array, true);
}
}
return result;
}