C# 实体类和DataTable相互转换

方法:

  1 /// <summary>
  2     /// DataTable转实体类集合
  3     /// </summary>
  4     /// <typeparam name="T"></typeparam>
  5     public class DataTableToEntity<T>where T:new()
  6     {
  7         /// <summary>
  8         /// table转实体集合
  9         /// </summary>
 10         /// <param name="dt"></param>
 11         /// <returns></returns>
 12         public List<T> FillModel(DataTable dt)
 13         {
 14             if (dt == null || dt.Rows.Count == 0)
 15                 return null;
 16             List<T> result = new List<T>();
 17             foreach (DataRow dr in dt.Rows)
 18             {
 19                 try
 20                 {
 21                     T res = new T();
 22                     for (int i = 0; i < dr.Table.Columns.Count; i++)
 23                     {
 24                         PropertyInfo propertyInfo = res.GetType().GetProperty(dr.Table.Columns[i].ColumnName, BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance);
 25                         if (propertyInfo != null && dr[i] != DBNull.Value)
 26                         {
 27                             var value = dr[i];
 28                             switch (propertyInfo.PropertyType.FullName)
 29                             {
 30                                 case "System.Decimal":
 31                                     propertyInfo.SetValue(res, Convert.ToDecimal(value), null); break;
 32                                 case "System.String":
 33                                     propertyInfo.SetValue(res, value, null); break;
 34                                 case "System.Int32":
 35                                     propertyInfo.SetValue(res, Convert.ToInt32(value), null); break;
 36                                 default:
 37                                     propertyInfo.SetValue(res, value, null); break;
 38                             }
 39                         }
 40                     }
 41                     result.Add(res);
 42                 }
 43                 catch (Exception ex)
 44                 {
 45                     CommonMethod.SaveText(dr.Table.TableName+"表id:" + dr[0] + "表第二项值:"+dr[1]+" 导出异常,异常信息:"+ex.Message+"
", Application.StartupPath + "\outFiles" + "\ErrorLog.txt");
 46                     continue;
 47                 }
 48                 
 49             }
 50             return result;
 51         }
 52 
 53         /// <summary>
 54         /// 读取json内容转成实体类集合
 55         /// </summary>
 56         /// <param name="path"></param>
 57         /// <returns></returns>
 58         public List<T> ReadDataToModel(string path)
 59         {
 60             StreamReader sr = new StreamReader(path);
 61             try
 62             {
 63                 string temp = sr.ReadToEnd();
 64                 return JsonConvert.DeserializeObject<List<T>>(temp);
 65             }
 66             catch (Exception)
 67             {
 68                 throw;
 69             }
 70             finally
 71             {
 72                 sr.Dispose();
 73                 sr.Close();
 74             }
 75         }
 76 
 77         /// <summary>
 78         /// 实体类集合转table
 79         /// </summary>
 80         /// <param name="model"></param>
 81         /// <returns></returns>
 82         public DataTable FillDataTable(List<T> modelList)
 83         {
 84             if (modelList == null || modelList.Count == 0)
 85                 return null;
 86             DataTable dt = CreatTable(modelList[0]);
 87             foreach (T model in modelList)
 88             {
 89                 DataRow dr = dt.NewRow();
 90                 foreach (PropertyInfo p in typeof(T).GetProperties())
 91                 {
 92                     dr[p.Name] = p.GetValue(model,null);
 93                 }
 94                 dt.Rows.Add(dr);
 95             }
 96             return dt;
 97         }
 98 
 99         /// <summary>
100         /// 根据实体创建table
101         /// </summary>
102         /// <param name="model"></param>
103         /// <returns></returns>
104         private DataTable CreatTable(T model)
105         {
106             DataTable dt = new DataTable(typeof(T).Name);
107             foreach (PropertyInfo p in typeof(T).GetProperties())
108             {
109                 dt.Columns.Add(new DataColumn(p.Name,p.PropertyType));
110             }
111             return dt;
112         } 
113     }
View Code

调用示例:

DataTable转成实体类集合示例:

List<Peak> peaks = new DataTableToEntity<Peak>().FillModel(peakDt);//Peak为实体类  peakDt为DataTable

实体类转成DataTable示例:

string abifilePath = Application.StartupPath + "\outFiles\peak\peak_111.json";
List<Abifile> abifiles = new DataTableToEntity<Abifile>().ReadDataToModel(abifilePath);
DataTable abifileDt = new DataTableToEntity<Abifile>().FillDataTable(abifiles); 
原文地址:https://www.cnblogs.com/wwr01/p/12572988.html