调用时传入参数 List<person> , 实体类person中的每个属性必须为公共属性,且必须含有{ get; set; } ,否则不能反射。
using System.Data;
using System.Reflection;
public static DataTable ToDataTable<T>(IEnumerable<T> collection)
{
PropertyInfo[] props = typeof(T).GetProperties();
DataTable dt = new DataTable();
dt.Columns.AddRange(props.Select(p => new DataColumn(p.Name, p.PropertyType)).ToArray());
if (collection.Count() > 0)
{
for (int i = 0; i < collection.Count(); i++)
{
ArrayList tempList = new ArrayList();
foreach (PropertyInfo pi in props)
{
object obj = pi.GetValue(collection.ElementAt(i), null);
tempList.Add(obj);
}
object[] array = tempList.ToArray();
dt.LoadDataRow(array, true);
}
}
return dt;
}
调用
List<person> persons= new List<person>();
DataTable dt = ToDataTable<person>(persons);