首页 > 其他分享 >DataTable与实体类的转换

DataTable与实体类的转换

时间:2022-10-29 23:25:53浏览次数:55  
标签:实体类 转换 List Sex new null DataTable

一、实现DataTable与实体类转换

  1 /***
  2 *    Title:"数据采集" 项目
  3 *        主题:表和实体帮助类
  4 *    Description:
  5 *        功能:
  6 *            1、DataTable指定行数据转化为实体类
  7 *            2、DataTable所有数据转换成实体类列表
  8 *            3、实体类列表转换成DataTable
  9 *    Date:2021
 10 *    Version:0.1版本
 11 *    Author:Coffee
 12 *    Modify Recoder:
 13 */
 14  
 15 using System;
 16 using System.Collections.Generic;
 17 using System.Data;
 18 using System.Linq;
 19 using System.Reflection;
 20 using System.Text;
 21 using System.Threading.Tasks;
 22  
 23 namespace Common
 24 {
 25     class TableToEntityHelper
 26     {
 27         /// <summary>
 28         /// DataTable指定行数据转化为实体类
 29         /// </summary>
 30         /// <typeparam name="T">实体类</typeparam>
 31         /// <param name="dataTable">dataTable</param>
 32         /// <param name="rowIndex">需要解析行的索引</param>
 33         /// <returns>返回当前指定行的实体类数据</returns>
 34         public static T DataTableToEntity<T>(DataTable dataTable,int rowIndex) where T : new()
 35         {
 36             try
 37             {
 38                 if (dataTable == null || dataTable.Rows.Count <= 0 || rowIndex<0)
 39                 {
 40                     return default(T);
 41                 }
 42  
 43                 //实例化实体类
 44                 T t = new T();
 45                 // 获取指定行数据
 46                 DataRow dr = dataTable.Rows[rowIndex];
 47                 // 获取所有列
 48                 DataColumnCollection columns = dataTable.Columns;
 49  
 50                 // 获得实体类的所有公共属性
 51                 PropertyInfo[] propertys = t.GetType().GetProperties();
 52                 foreach (PropertyInfo pi in propertys)
 53                 {
 54                     string name = pi.Name;
 55                     // 检查DataTable是否包含此列    
 56                     if (columns.Contains(name))
 57                     {
 58                         if (!pi.CanWrite) continue;
 59  
 60                         object value = dr[name];
 61                         if (value != DBNull.Value)
 62                         {
 63                             pi.SetValue(t, value, null);
 64                         }
 65                     }
 66                 }
 67                 return t;
 68  
 69             }
 70             catch (Exception)
 71             {
 72  
 73                 throw;
 74             }
 75         }
 76  
 77         /// <summary>
 78         /// DataTable所有数据转换成实体类列表
 79         /// </summary>
 80         /// <typeparam name="T">实体类</typeparam>
 81         /// <param name="dt">DataTable</param>
 82         /// <returns>返回实体类列表</returns>
 83         public static List<T> DataTableToList<T>(DataTable dt) where T : new()
 84         {
 85             try
 86             {
 87                 if (dt == null || dt.Rows.Count == 0)
 88                 {
 89                     return new List<T>();
 90                 }
 91  
 92                 // 实例化实体类和列表
 93              
 94                 List<T> list = new List<T>();
 95  
 96                 // 获取所有列
 97                 DataColumnCollection columns = dt.Columns;
 98  
 99                
100                 foreach (DataRow dr in dt.Rows)
101                 {
102                     T t = new T();
103                     // 获得实体类的所有公共属性
104                     PropertyInfo[] propertys = t.GetType().GetProperties();
105  
106                     //循环比对且赋值
107                     foreach (PropertyInfo p in propertys)
108                     {
109                         string name = p.Name;
110                         // 检查DataTable是否包含此列    
111                         if (columns.Contains(name))
112                         {
113                             if (!p.CanWrite) continue;
114  
115                             object value = dr[name];
116  
117                             if (value != DBNull.Value)
118                             {
119                                 是否需要转化
120                                 //if (value is int || value is float || value is decimal || value is double)
121                                 //{
122                                 //    p.SetValue(t, value.ToString(), null);
123                                 //}
124                                 //else
125                                 //{
126                                 //    p.SetValue(t, value, null);
127                                 //}
128  
129                                 p.SetValue(t, value, null);
130                             }
131                         }
132                     }
133                     list.Add(t);
134                 }
135                 return list;
136             }
137             catch (Exception ex)
138             {
139                 throw ex;
140             }
141         }
142  
143         /// <summary>
144         /// 实体类列表转换成DataTable
145         /// </summary>
146         /// <param name="entityList">实体类列表</param>
147         /// <param name="excludeFields">排除字段</param>
148         /// <returns>返回实体类列表对应的DataTable</returns>
149         public static DataTable ListToDataTable<T>(List<T> entityList, List<string> excludeFields = null)
150         {
151             var countExclude = 0;
152             if (excludeFields != null)
153                 countExclude = excludeFields.Count();
154  
155             //检查实体集合不能为空
156             if (entityList == null || entityList.Count <= 0)
157             {
158                 throw new Exception("需转换的集合为空");
159             }
160  
161             //取出第一个实体的所有属性
162             Type entityType = entityList[0].GetType();
163             PropertyInfo[] entityProperties = entityType.GetProperties();
164  
165  
166  
167             //实例化DataTable
168             DataTable dt = new DataTable();
169             for (int i = 0; i < entityProperties.Length; i++)
170             {
171                 Type colType = entityProperties[i].PropertyType;
172                 if ((colType.IsGenericType) && (colType.GetGenericTypeDefinition() == typeof(Nullable<>)))
173                 {
174                     colType = colType.GetGenericArguments()[0];
175                 }
176                 //排除列
177                 string fieldName = entityProperties[i].Name;
178                 if (excludeFields == null || !excludeFields.Contains(fieldName))
179                 {
180                     dt.Columns.Add(fieldName, colType);
181                 }
182             }
183  
184             //将所有entity添加到DataTable中
185             foreach (object entity in entityList)
186             {
187                 //检查所有的的实体都为同一类型
188                 if (entity.GetType() != entityType)
189                 {
190                     throw new Exception("要转换的集合元素类型不一致");
191                 }
192                 object[] entityValues = new object[dt.Columns.Count];
193                 int icount = 0;
194                 for (int i = 0; i < entityProperties.Length; i++)
195                 {
196                     //排除列
197                     string fieldName = entityProperties[i].Name;
198                     if (excludeFields == null || !excludeFields.Contains(fieldName))
199                     {
200                         entityValues[i - icount] = entityProperties[i].GetValue(entity, null);
201                     }
202                     else
203                     {
204                         icount++;
205                     }
206                 }
207                 dt.Rows.Add(entityValues);
208             }
209  
210             return dt;
211         }
212  
213  
214     }//Class_end
215  
216 }

二、使用方法

 1             //DataTable指定行数据转化为实体类
 2             //获取到当前选中的所有行
 3             int[] rows = gridView1.GetSelectedRows();
 4             if (rows!=null && rows.Length>0)
 5             {
 6                 //DataTable指定行数据转化为实体类
 7                 PeopleInfo peopleInfo = TableToEntityHelper.DataTableToEntity<PeopleInfo>(_dataTable, rows[0]);
 8             }
 9            
10  
11             //DataTable转换成实体类列表
12             List<PeopleInfo> peopleInfos = TableToEntityHelper.DataTableToList<PeopleInfo>(_dataTable);
13  
14  
15  
16             //需要排除的类字段
17             List<string> execlude = new List<string>()
18             {
19                "ID","Sex"
20             };
21             //实体类列表转换成DataTable
22             DataTable dt = TableToEntityHelper.ListToDataTable(GetPeopeoInfos(),execlude);
23             //DataTable转换成实体类列表(用于查看效果)
24             List<PeopleInfo> peopleInfos2 = TableToEntityHelper.DataTableToList<PeopleInfo>(dt);
25  
26  
27  
28  
29  
30   //模拟一个人员数据列表
31         private List<PeopleInfo> GetPeopeoInfos()
32         {
33             List<PeopleInfo> peopeoInfos = new List<PeopleInfo>()
34             {
35                 new PeopleInfo{ ID="JK001",FullName="杨万里",Sex="男",IdCard="523033199001026780"},
36                 new PeopleInfo{ ID="JK002",FullName="杨新宇",Sex="男",IdCard="523033199001026781"},
37                 new PeopleInfo{ ID="JK003",FullName="钟一明",Sex="男",IdCard="523033199001026782"},
38                 new PeopleInfo{ ID="JK004",FullName="张艺上",Sex="男",IdCard="523033199001026783"},
39                 new PeopleInfo{ ID="JK004",FullName=" ",Sex="男",IdCard="523033199001026784"},
40                 new PeopleInfo{ ID="JK006",FullName="胡一统",Sex="男",IdCard="523033199001026785"},
41                 new PeopleInfo{ ID="JK007",FullName="马国富",Sex="男",IdCard="523033199001026786"},
42                 new PeopleInfo{ ID="JK008",FullName="李宝军",Sex="男",IdCard="523033199001026787"},
43                 new PeopleInfo{ ID="JK009",FullName="软文策",Sex="男",IdCard="523033199001026788"},
44             };
45  
46  
47             return peopeoInfos;
48         }
49  
50  
51        //人员信息模型类
52         private class PeopleInfo
53         {
54             public string ID { get; set; }
55             public string FullName { get; set; }
56             public string Sex { get; set; }
57             public string IdCard { get; set; }
58         }

 

标签:实体类,转换,List,Sex,new,null,DataTable
From: https://www.cnblogs.com/lgx5/p/16840178.html

相关文章