将DataTable集合反射获取 List<M>

 /// <summary>
/// 根据DataTable集合反射获取 List<M>
/// </summary>
/// <typeparam name="M">泛型实体</typeparam>
/// <param name="dt">DataTable</param>
/// <returns>实体集合</returns>
private static List<M> SetValueRow<M>(DataTable dt) where M : new()
{
List<M> list = new List<M>(); Type type;
PropertyInfo p;
M m; foreach (DataRow row in dt.Rows)
{
m = new M();
type = m.GetType(); foreach (DataColumn col in dt.Columns)
{
//获取一个字段的属性
p = type.GetProperty(col.ColumnName); //实体中无对应属性
if (p == null)
continue; string colDbType = row[col.ColumnName].GetType().FullName; //结果集单元格中的值不为空时才赋值
if (colDbType != "System.DBNull")
{
switch (p.PropertyType.FullName)
{
case "System.Int64"://根据不同数据库数据类型作转换,如oracle的number(2)应转换为Int32,而不是默认的Decemal
p.SetValue(m, Convert.ToInt64(row[col.ColumnName]), null);
break; case "System.Int32":
p.SetValue(m, Convert.ToInt32(row[col.ColumnName]), null);
break; case "System.Int16":
p.SetValue(m, Convert.ToInt16(row[col.ColumnName]), null);
break; case "System.String":
p.SetValue(m, Convert.ToString(row[col.ColumnName]), null);
break; case "System.Decimal":
p.SetValue(m, Convert.ToDecimal(row[col.ColumnName]), null);
break; case "System.DateTime":
p.SetValue(m, row[col.ColumnName], null);
break; case "System.Double":
p.SetValue(m, Convert.ToDouble(row[col.ColumnName]), null);
break; case "System.Boolean":
p.SetValue(m, Convert.ToBoolean(row[col.ColumnName]), null);
break; case "System.Byte":
p.SetValue(m, Convert.ToByte(row[col.ColumnName]), null);
break; default:
p.SetValue(m, row[col.ColumnName], null);
break;
}
}
} list.Add(m);
} return list;
}

将IList集合类转换成DataTable

/// <summary>
/// 将IList集合类转换成DataTable
/// </summary>
/// <param name="list">集合</param>
/// <returns></returns>
public static DataTable IListToDataTable(IList list)
{
DataTable result = new DataTable();
if (list.Count > )
{
PropertyInfo[] propertys = list[].GetType().GetProperties();
foreach (PropertyInfo pi in propertys)
{
result.Columns.Add(pi.Name, pi.PropertyType);
} for (int i = ; i < list.Count; i++)
{
ArrayList tempList = new ArrayList();
foreach (PropertyInfo pi in propertys)
{
object obj = pi.GetValue(list[i], null);
tempList.Add(obj);
}
object[] array = tempList.ToArray();
result.LoadDataRow(array, true);
}
}
return result;
}
将List<M>集合类转换成DataTable 
        /// <summary>
/// 将List<M>集合类转换成DataTable
/// </summary>
/// <param name="list">集合</param>
/// <returns></returns>
public static DataTable IListToDataTable<M>(List<M> list)
{
DataTable result = new DataTable();
if (list.Count > )
{
PropertyInfo[] propertys = list[].GetType().GetProperties();
foreach (PropertyInfo pi in propertys)
{
result.Columns.Add(pi.Name, pi.PropertyType);
} for (int i = ; i < list.Count; i++)
{
ArrayList tempList = new ArrayList();
foreach (PropertyInfo pi in propertys)
{
object obj = pi.GetValue(list[i], null);
tempList.Add(obj);
}
object[] array = tempList.ToArray();
result.LoadDataRow(array, true);
}
}
return result;
}
全局静态类 泛型方法
/// <summary>
/// 全局静态类
/// </summary>
public static class GlobalStaticClass : Object
{ public static List<M> ToModelList<M>(this object obj) where M : new()
{
List<M> list = new List<M>(); Type type;
PropertyInfo p;
M m;
DataTable dt = (DataTable)obj; foreach (DataRow row in dt.Rows)
{
m = new M();
type = m.GetType(); foreach (DataColumn col in dt.Columns)
{
//获取一个字段的属性
p = type.GetProperty(col.ColumnName); //实体中无对应属性
if (p == null)
continue; string colDbType = row[col.ColumnName].GetType().FullName; //结果集单元格中的值不为空时才赋值
if (colDbType != "System.DBNull")
{
switch (p.PropertyType.FullName)
{
case "System.Int64"://根据不同数据库数据类型作转换,如oracle的number(2)应转换为Int32,而不是默认的Decemal
p.SetValue(m, Convert.ToInt64(row[col.ColumnName]), null);
break; case "System.Int32":
p.SetValue(m, Convert.ToInt32(row[col.ColumnName]), null);
break; case "System.Int16":
p.SetValue(m, Convert.ToInt16(row[col.ColumnName]), null);
break; case "System.String":
p.SetValue(m, Convert.ToString(row[col.ColumnName]), null);
break; case "System.Decimal":
p.SetValue(m, Convert.ToDecimal(row[col.ColumnName]), null);
break; case "System.DateTime":
p.SetValue(m, row[col.ColumnName], null);
break; case "System.Double":
p.SetValue(m, Convert.ToDouble(row[col.ColumnName]), null);
break; case "System.Boolean":
p.SetValue(m, Convert.ToBoolean(row[col.ColumnName]), null);
break; case "System.Byte":
p.SetValue(m, Convert.ToByte(row[col.ColumnName]), null);
break; default:
p.SetValue(m, row[col.ColumnName], null);
break;
}
}
} list.Add(m);
} return list;
} }

实体父类,实体继承此类后,实体对象可调用this.SetValue(object) 方法通过反射给自身对象赋值

    public class ModelBase
{
protected bool isNull = true;
public bool IsNull
{
get { return isNull; }
set { isNull = value; }
}
protected void SetValue(object info)
{
foreach (FieldInfo fi in info.GetType().GetFields(BindingFlags.NonPublic | BindingFlags.Instance))
{
this.GetType().GetField(fi.Name, BindingFlags.NonPublic | BindingFlags.Instance).SetValue(this, fi.GetValue(info));
}
}
public void SetValue(SqlDataReader dr)
{
if (dr.Read())
{
foreach (FieldInfo fi in this.GetType().GetFields(BindingFlags.NonPublic | BindingFlags.Instance))
{
if (fi.Name != "isNull")
{
object rel = dr[fi.Name];
if (dr[fi.Name] != Convert.DBNull)
{
fi.SetValue(this, dr[fi.Name]);
} }
}
this.isNull = false;
}
dr.Close();
}
public void SetValue(DataRow dr)
{
foreach (FieldInfo fi in this.GetType().GetFields(BindingFlags.NonPublic | BindingFlags.Instance))
{
if (fi.Name != "isNull")
{
if (dr.Table.Columns.Contains(fi.Name))
{
object rel = dr[fi.Name];
if (dr[fi.Name] != Convert.DBNull)
{
fi.SetValue(this, dr[fi.Name]);
}
}
}
}
this.isNull = false; } }

反射List<M> To DataTable|反射IList To DataTable|反射 DataTable To List<M>的更多相关文章

  1. c# 反射得到实体类的字段名称和值,DataTable转List<T>

    /// <summary> /// 反射得到实体类的字段名称和值 /// var dict = GetProperties(model); /// </summary> /// ...

  2. 完整DataTable与IList互换(转)

    public class CollectionHelper { private CollectionHelper() { } public static DataTable ConvertTo< ...

  3. Winform开发常用控件之DataGridView的简单数据绑定——代码绑定DataSet、DataTable、IList、SqlDataReader

    前文介绍了Winform为DataGridView提供的数据自动绑定功能,下面介绍一下采用代码的数据绑定 1.用DataSet和DataTable为DataGridView提供数据源 先上代码 pri ...

  4. 【2017001】IList转DataTable、DataTable转IList

    IList转DataTable.DataTable转IList using System; using System.Collections.Generic; using System.Compone ...

  5. Java反射获取class对象的三种方式,反射创建对象的两种方式

    Java反射获取class对象的三种方式,反射创建对象的两种方式 1.获取Class对象 在 Java API 中,提供了获取 Class 类对象的三种方法: 第一种,使用 Class.forName ...

  6. C#之DataTable转List与List转Datatable

    闲来无事,只有写代码啦,以下为DataTable转List与List转DataTable的两个方法,主要技术点用到了反射原理: /// <summary> /// 模型转换类 /// &l ...

  7. C# DataTable转List And List转DataTable

    // DataTable转List: IList<HousesEntity> Ilist = TableAndList.ConvertTo<HousesEntity>(dt); ...

  8. “DataTable”是“System.Data.DataTable”和“Microsoft.Office.Interop.Excel.DataTable”之间的不明确的引用

    “DataTable”是“System.Data.DataTable”和“Microsoft.Office.Interop.Excel.DataTable”之间的不明确的引用 造成这个错误的原因是,在 ...

  9. 多个不同的表合并到一个datatable中,repeater在绑定datatable

    using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.UI ...

  10. 将两个列不同的DataTable合并成一个新的DataTable

    /// <summary>         /// 将两个列不同(结构不同)的DataTable合并成一个新的DataTable         /// </summary> ...

随机推荐

  1. Java_4.1 猜数字游戏

    猜数字游戏: 系统随机产生一个1-100之间的数字,用户输入一个数字,如果用户输入的数字和随机数一样,输出“恭喜,猜对了”:如果猜大了,输出“猜大了”:如果猜小了,就输出“猜小了”. 循环直到用户输入 ...

  2. SSH异常“Failed to start OpenSSH Server daemon”

    [root@bogon yum]# systemctl status sshd.service● sshd.service - OpenSSH server daemon   Loaded: load ...

  3. html5的地理位置定位

    html5提供的地理位置定位使开发人员不用借助其他软件就能轻松实现位置查找,地图应用,导航等功能. 地理位置定位基本原理GPS, WIFI, IP, 手机信号基站 核心对象Geolocation是wi ...

  4. for循环中的 break和continue的区别

    break 语句用于跳出循环. for (i=0;i<10;i++) { if (i==3) { break; } x=x + "The number is " + i + ...

  5. 案例情景--在一次Oracle 数据库导出时 EXP-00008;ORA-00904:EXP-00000: oracle不同版本导入导出规则

    案例情景--在一次Oracle 数据库导出时: C:\Documents and Settings\Administrator>exp lsxy/lsxy@lsxy_db file=E:\lsx ...

  6. linux下查看内存使用情况

    基本内存术语解读 1> free -m 同样是做为缓存,buffers和cache又有啥区别呢? 于是又查了些资料,发现buffers实际应该是叫“缓冲”,其英文解释是:A buffer is ...

  7. BZOJ1935或洛谷2163 [SHOI2007]园丁的烦恼

    BZOJ原题链接 洛谷原题链接 很容易想到二维前缀和. 设\(S[i][j]\)表示矩阵\((0, 0)(i, j)\)内树木的棵数,则询问的矩形为\((x, y)(xx, yy)\)时,答案为\(S ...

  8. 洛谷4782 【模板】2-SAT 问题

    原题链接 \(2-SAT\)模板 #include<cstdio> using namespace std; const int N = 2e6 + 10; int fi[N], di[N ...

  9. Codeforces 791C. Bear and Different Names 模拟构造

    C. Bear and Different Names time limit per test:1 second memory limit per test:256 megabytes input:s ...

  10. 什么时候出现死锁,如何解决?mysql 引擎? 多个like or 查询sql如何优化?什么是常量池?for条件执行顺序

    1. 什么时候出现死锁,如何解决?mysql 引擎? 多个like or 查询sql如何优化? 资源竞争导致死锁,比如A B 同时操作两条记录,并等待对方释放锁. 优化sql, 加缓存,主从(如读写分 ...