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>;
}
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>;
}
相关文章推荐
- DataSet和List<T> 泛型之间互相转换 (转载, 作者写的很好)
- [摘]IList及泛型集合类转换DataTable
- DataTable数据集转换为List非泛型以及泛型方式
- [转]IList及泛型集合类转换DataTable
- C# DataTable 和List之间相互转换的方法
- DataTable转换list泛型集合(反射)
- 将DataTable转换成List<T>泛型集合助手类
- C# DataTable 和List之间相互转换的方法
- Datatable与实体list之间的转换
- 关于DataTable与IList和List泛型集合的相互转换在网上总结
- DataSet和List 泛型之间互相转换 (转载, 作者写的很好)
- DataSet和List<T> 泛型之间互相转换 (转载, 作者写的很好)
- C# DataTable 和List之间相互转换的方法[转]
- 将DataTable转换成泛型集合IList<>
- 将一个DataTable转换成一个List<T>的泛型集合
- DataTable、实体类Model和泛型List之间的转化
- List转DataTable(反射) ; 将泛型集合类转换成DataTable ; 将集合类转换成DataTable
- 将泛型list<>列表转换为Datatable
- list泛型转换成datatable
- DataSet和List<T> 泛型之间互相转换 (转载, 作者写的很好)