C# DataTable转List<Model>通用类
/// <summary>
/// DataTable转换为List<Model>
/// </summary>
public static class DataTableToListModel<T> where T : new()
{
public static IList<T> ConvertToModel(DataTable dt)
{
//定义集合
IList<T> ts = new List<T>();
T t = new T();
string tempName = "";
//获取此模型的公共属性
PropertyInfo[] propertys = t.GetType().GetProperties();
foreach (DataRow row in dt.Rows)
{
t = new T();
foreach (PropertyInfo pi in propertys)
{
tempName = pi.Name;
//检查DataTable是否包含此列
if (dt.Columns.Contains(tempName))
{
//判断此属性是否有set
if (!pi.CanWrite)
continue;
object value = row[tempName];
if (value != DBNull.Value)
pi.SetValue(t, value, null);
}
}
ts.Add(t);
}
return ts;
}
}
/// DataTable转换为List<Model>
/// </summary>
public static class DataTableToListModel<T> where T : new()
{
public static IList<T> ConvertToModel(DataTable dt)
{
//定义集合
IList<T> ts = new List<T>();
T t = new T();
string tempName = "";
//获取此模型的公共属性
PropertyInfo[] propertys = t.GetType().GetProperties();
foreach (DataRow row in dt.Rows)
{
t = new T();
foreach (PropertyInfo pi in propertys)
{
tempName = pi.Name;
//检查DataTable是否包含此列
if (dt.Columns.Contains(tempName))
{
//判断此属性是否有set
if (!pi.CanWrite)
continue;
object value = row[tempName];
if (value != DBNull.Value)
pi.SetValue(t, value, null);
}
}
ts.Add(t);
}
return ts;
}
}
作者:sy
出处:http://www.cnblogs.com/sydeveloper
QQ:522733724
本页版权归作者和博客园所有,欢迎转载,但未经作者同意必须保留此段声明,
且在文章页面明显位置给出原文链接,否则保留追究法律责任的权利