IList转DataTable、DataTable转IList

 using System;
 using System.Collections.Generic;
 using System.ComponentModel;
 using System.Data;
 using System.Linq;
 using System.Reflection;
 using System.Text;

 namespace Framework.Utility
 {
     public static class DataTableHelper
     {
         public static DataTable ConvertTo<T>(IList<T> list)
         {
             DataTable table = CreateTable<T>();
             Type entityType = typeof(T);
             PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(entityType);
             foreach (T item in list)
             {
                 DataRow row = table.NewRow();
                 foreach (PropertyDescriptor prop in properties)
                     row[prop.Name] = prop.GetValue(item);
                 table.Rows.Add(row);
             }
             return table;
         }

         public static IList<T> ConvertTo<T>(IList<DataRow> rows)
         {
             IList<T> list = null;
             if (rows != null)
             {
                 list = new List<T>();
                 foreach (DataRow row in rows)
                 {
                     T item = CreateItem<T>(row);
                     list.Add(item);
                 }
             }
             return list;
         }

         public static IList<T> ConvertTo<T>(DataTable table)
         {
             try
             {
                 if (table == null)
                     return null;

                 List<DataRow> rows = new List<DataRow>();
                 foreach (DataRow row in table.Rows)
                     rows.Add(row);

                 return ConvertTo<T>(rows);
             }
             catch(Exception ex)
             {
                 string err = ex.ToString();
                 return null;
             }
         }

         public static T CreateItem<T>(DataRow row)
         {
             string columnName;
             T obj = default(T);
             if (row != null)
             {
                 obj = Activator.CreateInstance<T>();
                 foreach (DataColumn column in row.Table.Columns)
                 {
                     columnName = column.ColumnName;
                     //Get property with same columnName
                     PropertyInfo prop = obj.GetType().GetProperty(columnName);
                     if (prop == null) continue;
                     ) continue;
                     try
                     {
                         //Get value for the column
                         object value = (row[columnName].GetType() == typeof(DBNull))
                         ? null : row[columnName];
                         //Set property value
                         if (prop.CanWrite)    //判断其是否可写
                             prop.SetValue(obj, value, null);
                     }
                     catch
                     {
                         throw;

                     }
                 }
             }
             return obj;
         }

         public static DataTable CreateTable<T>()
         {
             Type entityType = typeof(T);
             DataTable table = new DataTable(entityType.Name);
             PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(entityType);

             foreach (PropertyDescriptor prop in properties)
                 table.Columns.Add(prop.Name, prop.PropertyType);

             return table;
         }
         /// <summary>
         /// datatable 转换成list
         /// 调用方法:List<Entity> list = DataTableHelper.ConvertToEx<Entity>(dt);
         /// </summary>
         /// <typeparam name="T"></typeparam>
         /// <param name="dt"></param>
         /// <returns></returns>
         public static List<T> ConvertToEx<T>(DataTable dt) where T : new()
         {
             if (dt == null) return null;
             ) return null;

             List<T> list = new List<T>();
             Type type = typeof(T);
             PropertyInfo[] propertyInfos = type.GetProperties();  //获取泛型的属性
             List<DataColumn> listColumns = dt.Columns.Cast<DataColumn>().ToList();  //获取数据集的表头,以便于匹配
             T t;
             foreach (DataRow dr in dt.Rows)
             {
                 t = new T();
                 foreach (PropertyInfo propertyInfo in propertyInfos)
                 {
                     try
                     {
                         DataColumn dColumn = listColumns.Find(name => name.ToString().ToUpper() == propertyInfo.Name.ToUpper());  //查看是否存在对应的列名
                         if (dColumn != null)
                             propertyInfo.SetValue(t, dr[propertyInfo.Name], null);  //赋值
                     }
                     catch (Exception ex)
                     {
                         throw new Exception(ex.Message);
                     }
                 }
                 list.Add(t);
             }
             return list;
         }

     }
 }

【2017001】IList转DataTable、DataTable转IList的更多相关文章

  1. DataTable转换成IList<T>的简单实现

    DataTable的无奈 很多时候,我们需要去操作DataTable.但DataTable的操作,实在是太不方便了.Linq?lambda表达式?统统没有... 特别是对现有结果集做进一步筛选,这样的 ...

  2. C# IList<T>转为DataTable

    public class WebUtil { /// <summary> /// 转换IList<T>为DataTable/// </summary> /// &l ...

  3. C# 中 DataTable转换成IList

    在用C#作开发的时候经常要把DataTable转换成IList:操作DataTable比较麻烦,把DataTable转换成IList,以对象实体作为IList的元素,操作起来就非常方便. 注意:实体的 ...

  4. DataTable转换成IList 【转载】

    链接:http://www.cnblogs.com/hlxs/archive/2011/05/09/2087976.html#2738813 留着学习 using System; using Syst ...

  5. DataTable转换成IList

    //文章出处: http://www.cnblogs.com/hlxs/archive/2011/05/09/2087976.html DataTable转换成IList 在用C#作开发的时候经常要把 ...

  6. 将SqlDataReader 数据集转化为datatbale ,在将datatable 转化为iList

    public IList GetModelList(string tablename, string where) { IList list = null; DataTable dataTable = ...

  7. [DataTable] datatable根据表中的字段进行排序

    private DataTable SortTable(DataTable dt,string[] pids) { DataTable dt0 = dt.Clone(); //复制原表结构 ;i< ...

  8. MVC中一般为什么用IQueryable而不是用IList?用IQueryable比IList好在哪?

    IList(IList<T>)会立即在内存里创建持久数据,这就没有实现"延期执行(deferred execution)",如果被加载的实体有关联实体(associat ...

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

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

随机推荐

  1. @media print样式 关于table断页

    <html> <head> <style> @media print { table { page-break-after:auto } tr { page-bre ...

  2. 反编译DLL文件

    我们平时在工作中经常会遇到一些已经被编译后的DLL,而且更加麻烦是没有源代码可以进行修改,只能针对这个DLL的文件进行修改才能得到我们想要的结果:本文将通过一个实例来演示如果完成一个简单的修改;我们将 ...

  3. sql: T-SQL parent-child function script

    --Parent-Child reationship --涂聚文 2014-08-25 --得位置的子節點函數表(包含本身) if exists (select * from dbo.sysobjec ...

  4. 利用 Task\Query 实现定位 , FeatureLayer 的属性查询

    放纵了几天,又有了学习的动力.今天实现了利用对 FeatureLayer 进行属性查询在地图上进行跳转. 一.我下载了一幅浙江省的县界面地图,存在NAME字段,利用Name就能进行查询了: var n ...

  5. C#链接数据库:SQL Server 2008

    自己学习C#编程,在WinForm编程中,代码测试连接数据库. 现在sqlserver中测试使用的数据库能否以指定的用户名和密码登录. 如图所示,计算机名为administrator,数据库实例为sq ...

  6. mybatis支持的jdbc类型

    参考mybatis的枚举JdbcType源码: 关于这些类型mybatis是如何处理可以看一下TypeHandler类的源码.

  7. Linux ->> Ubuntu 14.04 LTE下安装JDK 1.8

    先到Oracle官网的下载中心下载JDK8的tar包到本地. 下载地址:http://www.oracle.com/technetwork/java/javase/downloads/jdk8-dow ...

  8. mongodb 3.4分片复制集配置

    1:启动三个实例 mongod -f /home/mongodb/db27017/mongodb27017.conf mongod -f /home/mongodb/db27018/mongodb27 ...

  9. /usr/lib64/python2.6/site-packages/cryptography/__init__.py:26: DeprecationWarning: Python 2.6 is no longer supported by the Python core team

    升级python2.6到2.7后,执行ansible后一直显示警告,如标题所示. 因为安装ansible,使用的是yum的方式,而yum使用的是python2.6,所以ansible安装环境为pyth ...

  10. ipsec验证xl2tpd报错:handle_packet: bad control packet!

    使用ipsec和xl2tpd搭建好vpn后,使用ipsec密钥方式不能连接,显示 “连接的时候被远程服务器中止” 使用xl2tpd -D查看连接情况,尝试连接了许多次,错误如下: 开始不确定问题所在, ...