您的位置:首页 > 其它

List 与 DataTable之间的转换 (应用泛型)

2009-12-28 13:28 525 查看
一个老外写的,关于List 于 DataTable之间的转换,学习下,原文找不到了,抱歉

public static DataTable ListToDataTable<T>(List<T> list)
{
DataTable dt = new DataTable();

foreach (PropertyInfo info in typeof(T).GetProperties())
{
dt.Columns.Add(new DataColumn(info.Name, info.PropertyType));
}
foreach (T t in list)
{
DataRow row = dt.NewRow();
foreach (PropertyInfo info in typeof(T).GetProperties())
{
row[info.Name] = info.GetValue(t, null);
}
dt.Rows.Add(row);
}
return dt;
}

public static IList<T> ConvertTo<T>(DataTable table)
{
if (table == null)
return null;
List<DataRow> rows = new List<DataRow>();
foreach (DataRow row in table.Rows)
rows.Add(row);
return rows as IList<T>;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: