Datatable与实体list之间的转换
2015-01-29 06:28
381 查看
public static class ConvertDataTableWithList<T> where T:new()
{
public static List<T> ConvertToModelList(DataTable dt)
{
//定义集合
List<T> ts = new List<T>();
T t = new T();
//获取此模型的公共属性
PropertyInfo[] propertys = t.GetType().GetProperties();
foreach (DataRow row in dt.Rows)
{
t = new T();
foreach (PropertyInfo pi in propertys)
{
//检查DataTable是否包含此列
if (dt.Columns.Contains(pi.Name))
{
//判断此属性是否有set
if (!pi.CanWrite)
continue;
object value = row[pi.Name];
if (value != DBNull.Value)
pi.SetValue(t, value, null);
}
}
ts.Add(t);
}
return ts;
}
public static DataTable ConvertToDataTable(List<T> list)
{
DataTable dt=new DataTable();
T t=new T();
PropertyInfo [] propertys=t.GetType().GetProperties();
//给datatable添加列
foreach (PropertyInfo pi in propertys)
{
dt.Columns.Add(pi.Name);
}
dt.AcceptChanges();
foreach (T item in list)
{
t = new T();
DataRow dr = dt.NewRow();
foreach (PropertyInfo pi in propertys)
{
if (!pi.CanWrite)
continue;
dr[pi.Name] = pi.GetValue(t);
}
dt.Rows.Add(dr);
}
dt.AcceptChanges();
return dt;
}
}
{
public static List<T> ConvertToModelList(DataTable dt)
{
//定义集合
List<T> ts = new List<T>();
T t = new T();
//获取此模型的公共属性
PropertyInfo[] propertys = t.GetType().GetProperties();
foreach (DataRow row in dt.Rows)
{
t = new T();
foreach (PropertyInfo pi in propertys)
{
//检查DataTable是否包含此列
if (dt.Columns.Contains(pi.Name))
{
//判断此属性是否有set
if (!pi.CanWrite)
continue;
object value = row[pi.Name];
if (value != DBNull.Value)
pi.SetValue(t, value, null);
}
}
ts.Add(t);
}
return ts;
}
public static DataTable ConvertToDataTable(List<T> list)
{
DataTable dt=new DataTable();
T t=new T();
PropertyInfo [] propertys=t.GetType().GetProperties();
//给datatable添加列
foreach (PropertyInfo pi in propertys)
{
dt.Columns.Add(pi.Name);
}
dt.AcceptChanges();
foreach (T item in list)
{
t = new T();
DataRow dr = dt.NewRow();
foreach (PropertyInfo pi in propertys)
{
if (!pi.CanWrite)
continue;
dr[pi.Name] = pi.GetValue(t);
}
dt.Rows.Add(dr);
}
dt.AcceptChanges();
return dt;
}
}
相关文章推荐
- 将Datatable转换成实体List集合的方法
- C# DataTable 和List之间相互转换的方法
- JSON 格式的转换: 数组、字符串、List集合、DataTable,实体对象
- DataTable与结构不同实体类之间的转换
- asp.net中DataTable和List<T>之间相互转换
- C# DataTable 和List之间相互转换的方法
- C# DataTable 和List之间相互转换的方法
- C# DataTable 和List之间相互转换的方法
- 转 C# DataTable 和List之间相互转换的方法
- C#将DataTable转换成单个T实体和List<T>集合
- 将List实体转换成DataTable
- DataRow/DataTable 与实体类之间的转换
- C# DataTable 和List之间相互转换的方法[转]
- DataTable转List<Model>通用类【实体转换辅助类】
- C# DataTable 和List之间相互转换的方法
- Datatable转换成List实体对象列表 几个实例
- Datatable转换成List实体对象列表
- 实体对象,List泛型 转换为DataTable
- XML与实体类,DataTable,List之间进行转换
- (转)DataTable与结构不同实体类之间的转换