List转换DataTable

 

List转换DataTable

public static DataTable ToDataTable<T>(this IEnumerable<T> results)
{
var resultTable = new DataTable();
var properties = typeof(T).GetProperties();


foreach (var info in properties)
{
var vtype = info.PropertyType;
if (vtype == typeof(double?))
{
vtype = typeof(double);
}
if (vtype == typeof(decimal?))
{
vtype = typeof(decimal);
}
if (vtype == typeof(DateTime?))
{
vtype = typeof(DateTime);
}
if (vtype == typeof(int?))
{
vtype = typeof(int);
}
if (vtype == typeof(Guid?))
{
vtype = typeof(Guid);
}
resultTable.Columns.Add(info.Name, vtype);
}


foreach (T result in results)
{
var dr = resultTable.NewRow();
foreach (var info in properties)
{
if (info.CanRead)
{
dr[info.Name] = info.GetValue(result, null) ?? DBNull.Value;
}
}
resultTable.Rows.Add(dr);
}
return resultTable;
}

posted @ 2013-08-23 14:02  Loser0628  阅读(198)  评论(0编辑  收藏  举报