读书人

将实体类会合转换为DataTable

发布时间: 2013-03-13 10:56:58 作者: rapoo

将实体类集合转换为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中的Timesstarmp类型
{


dataTable.Columns.Add(new DataColumn(propertyInfo.Name, propertyInfo.PropertyType));
}
else
{
dataTable.Columns.Add(new DataColumn(propertyInfo.Name, typeof(DateTime)));
}
}
return dataTable;
}
如上是一个将实体类集合转换为DataTable类型的方法。。但是我用在我的方法里执行不进去,谁能找找原因,或者给出正确的。方法。 Datatable?实体类
[解决办法]

class Program
{
static void Main(string[] args)
{
var list = new List<Demo> {
new Demo{ id=1,age=18, name="Tim"},
new Demo{ id=2,age=22, name="Allen"},
new Demo{ id=3,age=24, name="Jim"}
};
var dt = list.ToDataTable();

}
}
static class Extensions
{
internal static DataTable ToDataTable<T>(this IList<T> list)
{
Type elementType = typeof(T);

var t = new DataTable();

elementType.GetProperties().ToList().ForEach(propInfo => t.Columns.Add(propInfo.Name, Nullable.GetUnderlyingType(propInfo.PropertyType) ?? propInfo.PropertyType));
foreach (T item in list)
{
var row = t.NewRow();
elementType.GetProperties().ToList().ForEach(propInfo => row[propInfo.Name] = propInfo.GetValue(item, null) ?? DBNull.Value);


t.Rows.Add(row);
}
return t;
}
}
class Demo
{
public int id { get; set; }
public string name { get; set; }
public int age { get; set; }
}

读书人网 >C#

热点推荐