IList转DataTable、DataTable转IList

  1 using System;
  2 using System.Collections.Generic;
  3 using System.ComponentModel;
  4 using System.Data;
  5 using System.Linq;
  6 using System.Reflection;
  7 using System.Text;
  8
  9 namespace Framework.Utility
 10 {
 11     public static class DataTableHelper
 12     {
 13         public static DataTable ConvertTo<T>(IList<T> list)
 14         {
 15             DataTable table = CreateTable<T>();
 16             Type entityType = typeof(T);
 17             PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(entityType);
 18             foreach (T item in list)
 19             {
 20                 DataRow row = table.NewRow();
 21                 foreach (PropertyDescriptor prop in properties)
 22                     row[prop.Name] = prop.GetValue(item);
 23                 table.Rows.Add(row);
 24             }
 25             return table;
 26         }
 27
 28         public static IList<T> ConvertTo<T>(IList<DataRow> rows)
 29         {
 30             IList<T> list = null;
 31             if (rows != null)
 32             {
 33                 list = new List<T>();
 34                 foreach (DataRow row in rows)
 35                 {
 36                     T item = CreateItem<T>(row);
 37                     list.Add(item);
 38                 }
 39             }
 40             return list;
 41         }
 42
 43         public static IList<T> ConvertTo<T>(DataTable table)
 44         {
 45             try
 46             {
 47                 if (table == null)
 48                     return null;
 49
 50                 List<DataRow> rows = new List<DataRow>();
 51                 foreach (DataRow row in table.Rows)
 52                     rows.Add(row);
 53
 54                 return ConvertTo<T>(rows);
 55             }
 56             catch(Exception ex)
 57             {
 58                 string err = ex.ToString();
 59                 return null;
 60             }
 61         }
 62
 63
 64         public static T CreateItem<T>(DataRow row)
 65         {
 66             string columnName;
 67             T obj = default(T);
 68             if (row != null)
 69             {
 70                 obj = Activator.CreateInstance<T>();
 71                 foreach (DataColumn column in row.Table.Columns)
 72                 {
 73                     columnName = column.ColumnName;
 74                     //Get property with same columnName
 75                     PropertyInfo prop = obj.GetType().GetProperty(columnName);
 76                     if (prop == null) continue;
 77                     if (row.Table.Columns.IndexOf(columnName) == -1) continue;
 78                     try
 79                     {
 80                         //Get value for the column
 81                         object value = (row[columnName].GetType() == typeof(DBNull))
 82                         ? null : row[columnName];
 83                         //Set property value
 84                         if (prop.CanWrite)    //判断其是否可写
 85                             prop.SetValue(obj, value, null);
 86                     }
 87                     catch
 88                     {
 89                         throw;
 90
 91                     }
 92                 }
 93             }
 94             return obj;
 95         }
 96
 97         public static DataTable CreateTable<T>()
 98         {
 99             Type entityType = typeof(T);
100             DataTable table = new DataTable(entityType.Name);
101             PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(entityType);
102
103             foreach (PropertyDescriptor prop in properties)
104                 table.Columns.Add(prop.Name, prop.PropertyType);
105
106             return table;
107         }
108         /// <summary>
109         /// datatable 转换成list
110         /// 调用方法:List<Entity> list = DataTableHelper.ConvertToEx<Entity>(dt);
111         /// </summary>
112         /// <typeparam name="T"></typeparam>
113         /// <param name="dt"></param>
114         /// <returns></returns>
115         public static List<T> ConvertToEx<T>(DataTable dt) where T : new()
116         {
117             if (dt == null) return null;
118             if (dt.Rows.Count <= 0) return null;
119
120             List<T> list = new List<T>();
121             Type type = typeof(T);
122             PropertyInfo[] propertyInfos = type.GetProperties();  //获取泛型的属性
123             List<DataColumn> listColumns = dt.Columns.Cast<DataColumn>().ToList();  //获取数据集的表头,以便于匹配
124             T t;
125             foreach (DataRow dr in dt.Rows)
126             {
127                 t = new T();
128                 foreach (PropertyInfo propertyInfo in propertyInfos)
129                 {
130                     try
131                     {
132                         DataColumn dColumn = listColumns.Find(name => name.ToString().ToUpper() == propertyInfo.Name.ToUpper());  //查看是否存在对应的列名
133                         if (dColumn != null)
134                             propertyInfo.SetValue(t, dr[propertyInfo.Name], null);  //赋值
135                     }
136                     catch (Exception ex)
137                     {
138                         throw new Exception(ex.Message);
139                     }
140                 }
141                 list.Add(t);
142             }
143             return list;
144         }
145
146     }
147 }

转载于:https://www.cnblogs.com/hghg/p/7889724.html

【2017001】IList转DataTable、DataTable转IList相关推荐

  1. DataTable转换成IList

    本文转载自http://blog.csdn.net/chentaihan/article/details/6407284 作者:陈太汉     在用C#作开发的时候经常要把DataTable转换成IL ...

  2. C# dataTable 转 IList 问题

    大家在使用.NET开发时把查询结果以DataTable返回很方便,但是在检索数据时又很麻烦,没有模型类型检索方便. 所以很多人都是按照以下方式做的: // 获得查询结果 DataTable dt = ...

  3. IList类转换成DataTable

    /// <summary>/// 将集合类转换成DataTable/// </summary>/// <param name="list">集合 ...

  4. DataTable转ListModel通用类

    /// <summary> /// DataTable转List<Model>通用类[实体转换辅助类] /// </summary> public class Mo ...

  5. Ilist与List的区别

    首先要了解一点的是关于接口的基础知识: 接口不能直接实例化 但是接口派生出来的抽象类可以实例化 所有派生出来的抽象类都可以强制转换成接口的实例 第三条我解释一下:比如,IList <Class& ...

  6. .Net 中HashTable,HashMap 和 Dictionarykey,value 和ListT和DataTable的比较

    转载自http://www.cnblogs.com/jilodream/p/4219840.html (一)HashTable    和Dic    数据结构 Hashtable和Dictionary ...

  7. C# DataTable转ListModel通用类

    /// <summary> /// DataTable转换为List<Model> /// </summary> public static class DataT ...

  8. List转DataTable(反射)

    /// <summary>         /// 将集合类转换成DataTable         /// </summary>         /// <param ...

  9. DataTable转成List集合

    项目开发中,经常会获取到DataTable对象,如何把它转化成一个List对象呢?前几天就碰到这个问题,网上搜索整理了一个万能类,用了泛型和反射的知识.共享如下: public class Model ...

最新文章

  1. 深度 | 推荐系统评估
  2. WPF Calendar 日历控件 样式自定义
  3. Java智慧社区商业级别项目源码,拿来学习真不错
  4. 中国男人何时回归家庭?(转)
  5. java 内省学习笔记
  6. 2017.7.19 Race 思考记录
  7. 【云笔记搭建】Visual Code + Github仓库 + Git
  8. Access链接表的使用
  9. 怎么用EasyRecovery恢复硬盘内被误删的数据
  10. nginx配置http访问自动跳转到https
  11. stm32 国产QMC5883L 进口HMC5883 三轴电子指南针加速度传感器
  12. 一千本免费电子书(建议长期保存)转的-用迅雷下载
  13. 计算机房应配置灭火器,下列哪种灭火器配置是正确的?
  14. 科技业10大错误决定
  15. 忠魁互联优化:头条SEO全网搜索营销怎么做?
  16. 手机流量不清零这个便宜不好占
  17. 证券公司信息化——8
  18. 前端学习:jQuery学习--Day03
  19. 数字电路中的建立时间与保持时间是什么
  20. Springer投稿流程——Multimedia Tools and Applications

热门文章

  1. 更新!机器学习手推笔记《规则学习》
  2. c++中enum 如何使用(转)
  3. php 日期format不要零_PHP格式化日期用法代码,包括前导零示例
  4. 计算机考研408试题及答案,2015年计算机专业408考研试题及答案
  5. 华为鸿蒙系统学习笔记2-生态系统介绍
  6. Android SDK实例之Snake游戏深入解析(一)
  7. python 接口自动化的sql验证_基于Python的接口自动化实战-基础篇之pymysql模块操做数据库...
  8. 一个学校内部的计算机网络属于,一个教室内计算机联成的网络属于____。
  9. 条件渲染-v-if // v-else // v-else if // v-show
  10. 读取properties文件,中文乱码