/// <summary>
/// 枚举转换dataTable
/// </summary>
/// <param name="result"></param>
/// <returns></returns>
public DataTable GetTableFromEnum<T>(IEnumerable<T> collection)
{
var props = typeof(T).GetProperties();
var dt = new DataTable();
//创建
dt.Columns.AddRange
(
//可空类型转换为值类型,内部处理异常及内部对象
props.Select
(
p => new DataColumn(p.Name, ToStruct(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;
}
值类型转换方法:ToStruct
网友评论