/// <summary>
/// 生成DataTable
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="collection"></param>
/// <returns></returns>
private DataTable ListToDataTable<T>(List<T> collection)
{
var dt = new DataTable();
if (collection.Count <= 0) return dt;
var props = typeof(T).GetProperties();
dt.Columns.AddRange(props.Select(p =>
{
var colType = p.PropertyType;
if ((colType.IsGenericType) && (colType.GetGenericTypeDefinition() == typeof(Nullable<>)))
{
colType = colType.GetGenericArguments()[0];
}
var dc = new DataColumn(p.Name, colType);
return dc;
}).ToArray());
for (int i = 0; i < collection.Count; i++)
{
var tempList = new ArrayList();
foreach (PropertyInfo pi in props)
{
object obj = pi.GetValue(collection.ElementAt(i), null);
tempList.Add(obj);
}
var array = tempList.ToArray();
dt.LoadDataRow(array, true);
}
return dt;
}