public static DataTable ListToDT<T>(List<T> ls)
{
DataTable dt = new DataTable();
Type tp = typeof(T);
PropertyInfo[] pinfo = tp.GetProperties();
foreach (PropertyInfo pi in pinfo)
{
dt.Columns.Add(pi.Name);
}
if (ls != null)
{
for (int i = 0; i < ls.Count; i++)
{
IList TempList = new ArrayList();
foreach (System.Reflection.PropertyInfo pi in pinfo)
{
object oo = pi.GetValue(ls[i], null);
TempList.Add(oo);
}
object[] itm = new object[pinfo.Length];
//遍历ArrayList向object[]里放数据
for (int j = 0; j < TempList.Count; j++)
{
itm.SetValue(TempList[j], j);
}
//将object[]的内容放入DataTable
dt.LoadDataRow(itm, true);
}
}
return dt;
}