DataTable转成实体列表 和 DataRow转成实体类

 1         #region DataTale转为实体列表  
 2         /// <summary>  
 3         /// DataTale转为实体列表  
 4         /// </summary>  
 5         /// <typeparam name="T">实体类类型</typeparam>  
 6         /// <param name="table">DataTable</param>  
 7         /// <returns>List<T></returns>  
 8         public List<T> DataTableToModelList<T>(DataTable table)
 9         {
10             List<T> list = new List<T>();
11             T t = default(T);
12             PropertyInfo[] propertypes = null;
13             string tempName = string.Empty;
14             foreach (DataRow row in table.Rows)
15             {
16                 t = Activator.CreateInstance<T>();
17                 propertypes = t.GetType().GetProperties();
18                 foreach (PropertyInfo pro in propertypes)
19                 {
20                     tempName = pro.Name;
21                     if (table.Columns.Contains(tempName))
22                     {
23                         object value = row[tempName];
24                         if (value.GetType() == typeof(System.DBNull))
25                         {
26                             value = null;
27                         }
28                         pro.SetValue(t, value, null);
29                     }
30                 }
31                 list.Add(t);
32             }
33             return list;
34         }
35         #endregion
36 
37         #region   DataRow转为实体类  
38         /// <summary>  
39         /// DataRow转为实体类  
40         /// </summary>  
41         /// <typeparam name="T">实体类类型</typeparam>  
42         /// <param name="row">DataRow</param>  
43         /// <returns>T</returns>  
44         public T DataRowToModel<T>(DataRow row)
45         {
46 
47             T t = default(T);
48             PropertyInfo[] propertypes = null;
49             string tempName = string.Empty;
50             t = Activator.CreateInstance<T>();
51             propertypes = t.GetType().GetProperties();
52             foreach (PropertyInfo pro in propertypes)
53             {
54                 tempName = pro.Name;
55                 if (row.Table.Columns.Contains(tempName))
56                 {
57                     object value = row[tempName];
58                     if (value.GetType() == typeof(System.DBNull))
59                     {
60                         value = null;
61                     }
62                     pro.SetValue(t, value, null);
63                 }
64             }
65             return t;
66         }
67         #endregion

学习记录

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值