将实体类集合转换为DataTable
通过反射将实体类转化为DataTable类型
using System.Reflection;
using System.Data;
/// <summary>
/// 实体类转换成DataTable
/// 调用示例:DataTable dt= FillDataTable(Entitylist.ToList());
/// </summary>
/// <param name="modelList">实体类列表</param>
/// <returns></returns>
public DataTable FillDataTable<T>(List<T> modelList)
{
if (modelList == null || modelList.Count == 0)
{
return null;
}
DataTable dt = CreateData(modelList[0]);//创建表结构
foreach (T model in modelList)
{
DataRow dataRow = dt.NewRow();
foreach (PropertyInfo propertyInfo in typeof(T).GetProperties())
{
dataRow[propertyInfo.Name] = propertyInfo.GetValue(model, null);
}
dt.Rows.Add(dataRow);
}
return dt;
}
/// <summary>
/// 根据实体类得到表结构
/// </summary>
/// <param name="model">实体类</param>
/// <returns></returns>
private DataTable CreateData<T>(T model)
{
DataTable dataTable = new DataTable(typeof(T).Name);
foreach (PropertyInfo propertyInfo in typeof(T).GetProperties())
{
if (propertyInfo.Name != "CTimestamp")//些字段为oracle中的Tim