//文章出处:

http://www.cnblogs.com/hlxs/archive/2011/05/09/2087976.html 

DataTable转换成IList

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

注意:实体的属性必须和数据库中的字段必须一一对应,或者数据库字段名.ToLower().Contains(实体属性名.ToLower())

          数据类型暂时至支持int、string、DateTime、float、double

 

  1. using System;
    using System.Collections;
    using System.Collections.Generic;
    using System.Data;
    using System.Reflection;
  2.  
  3. namespace TBToListTest
    {
    public class TBToList<T> where T : new()
    {
    /// <summary>
    /// 获取列名集合
    /// </summary>
    private IList<string> GetColumnNames(DataColumnCollection dcc)
    {
    IList<string> list = new List<string>();
    foreach (DataColumn dc in dcc)
    {
    list.Add(dc.ColumnName);
    }
    return list;
    }
  4.  
  5. /// <summary>
    ///属性名称和类型名的键值对集合
    /// </summary>
    private Hashtable GetColumnType(DataColumnCollection dcc)
    {
    if (dcc == null || dcc.Count == 0)
    {
    return null;
    }
    IList<string> colNameList = GetColumnNames(dcc);
  6.  
  7. Type t = typeof(T);
    PropertyInfo[] properties = t.GetProperties();
    Hashtable hashtable = new Hashtable();
    int i = 0;
    foreach (PropertyInfo p in properties)
    {
    foreach (string col in colNameList)
    {
    if (col.ToLower().Contains(p.Name.ToLower()))
    {
    hashtable.Add(col, p.PropertyType.ToString() + i++);
    }
    }
    }
  8.  
  9. return hashtable;
    }
  10.  
  11. /// <summary>
    /// DataTable转换成IList
    /// </summary>
    /// <param name="dt"></param>
    /// <returns></returns>
    public IList<T> ToList(DataTable dt)
    {
    if (dt == null || dt.Rows.Count == 0)
    {
    return null;
    }
  12.  
  13. PropertyInfo[] properties = typeof(T).GetProperties();//获取实体类型的属性集合
    Hashtable hh = GetColumnType(dt.Columns);//属性名称和类型名的键值对集合
    IList<string> colNames = GetColumnNames(hh);//按照属性顺序的列名集合
    List<T> list = new List<T>();
    T model = default(T);
    foreach (DataRow dr in dt.Rows)
    {
    model = new T();//创建实体
    int i = 0;
    foreach (PropertyInfo p in properties)
    {
    if (p.PropertyType == typeof(string))
    {
    p.SetValue(model, dr[colNames[i++]], null);
    }
    else if (p.PropertyType == typeof(int))
    {
    p.SetValue(model, int.Parse(dr[colNames[i++]].ToString()), null);
    }
    else if (p.PropertyType == typeof(DateTime))
    {
    p.SetValue(model, DateTime.Parse(dr[colNames[i++]].ToString()), null);
    }
    else if (p.PropertyType == typeof(float))
    {
    p.SetValue(model, float.Parse(dr[colNames[i++]].ToString()), null);
    }
    else if (p.PropertyType == typeof(double))
    {
    p.SetValue(model, double.Parse(dr[colNames[i++]].ToString()), null);
    }
    }
  14.  
  15. list.Add(model);
    }
  16.  
  17. return list;
    }
  18.  
  19. /// <summary>
    /// 按照属性顺序的列名集合
    /// </summary>
    private IList<string> GetColumnNames(Hashtable hh)
    {
    PropertyInfo[] properties = typeof(T).GetProperties();//获取实体类型的属性集合
    IList<string> ilist = new List<string>();
    int i = 0;
    foreach (PropertyInfo p in properties)
    {
    ilist.Add(GetKey(p.PropertyType.ToString() + i++, hh));
    }
    return ilist;
    }
  20.  
  21. /// <summary>
    /// 根据Value查找Key
    /// </summary>
    private string GetKey(string val, Hashtable tb)
    {
    foreach (DictionaryEntry de in tb)
    {
    if (de.Value.ToString() == val)
    {
    return de.Key.ToString();
    }
    }
    return null;
    }
  22.  
  23. }
    }
  24.  
  25. namespace TBToListTest
    {
  26.  
  27. //实体
    public class Person
    {
    public int ID
    {
    set;
    get;
    }
  28.  
  29. public string Name
    {
    set;
    get;
    }
  30.  
  31. public string Age
    {
    set;
    get;
    }
  32.  
  33. public string Lover
    {
    set;
    get;
    }
  34.  
  35. }
    }
  36.  
  37. using System;
    using System.Data;
  38.  
  39. namespace TBToListTest
    {
    class Program
    {
    static void Main(string[] args)
    {
    TBToList<Person> tol = new TBToList<Person>();
    Console.WriteLine();
    DataTable dt = GetTable();
    tol.ToList(dt);
    Console.Read();
    }
  40.  
  41. public static DataTable GetTable()
    {
    DataTable dt = new DataTable();
    dt.Columns.Add("ID");
    dt.Columns.Add("Age");
    dt.Columns.Add("Lover");
    dt.Columns.Add("Name");
    DataRow dr = dt.NewRow();
    dr["ID"] = 1;
    dr["Age"] = "Age1";
    dr["Lover"] = "Lover1";
    dr["Name"] = "Name1";
    dt.Rows.Add(dr);
    DataRow dr1 = dt.NewRow();
    dr1["ID"] = 2;
    dr1["Age"] = "Age2";
    dr1["Lover"] = "Lover2";
    dr1["Name"] = "Name2";
    dt.Rows.Add(dr1);
    return dt;
    }
    }
    }

DataTable转换成IList的更多相关文章

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

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

  2. C# 中 DataTable转换成IList

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

  3. DataTable转换成IList 【转载】

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

  4. C# DataTable转换成实体列表 与 实体列表转换成DataTable

    /// <summary> /// DataTable转换成实体列表 /// </summary> /// <typeparam name="T"&g ...

  5. DataTable转换成匿名类的List类型

    DataTable转换成匿名类的List类型   因为匿名类是不能够 Activator.CreateInstance进行反射实例化的 /// <summary> /// 匿名类的转换方式 ...

  6. DataTable 转换成 Json的3种方法

    在web开发中,我们可能会有这样的需求,为了便于前台的JS的处理,我们需要将查询出的数据源格式比如:List<T>.DataTable转换为Json格式.特别在使用Extjs框架的时候,A ...

  7. asp.net dataTable转换成Json格式

    /// <summary> /// dataTable转换成Json格式 /// </summary> /// <param name="dt"> ...

  8. 将DataTable转换成CSV文件

    DataTable用于在.net项目中,用于缓存数据,DataTable表示内存中数据的一个表.CSV文件最早用在简单的数据库里,由于其格式简单,并具备很强的开放性,所以起初被扫图家用作自己图集的标记 ...

  9. 将DataSet(DataTable)转换成JSON格式(生成JS文件存储)

    public static string CreateJsonParameters(DataTable dt) { /**/ /**/ /**/ /* /*********************** ...

随机推荐

  1. hdu 1560(IDA*)

    题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1560 思路:关键是启发式函数h()的构造,我们可以这样想:每次给主串增加一个字符和字符串的最后一位比较 ...

  2. python3----输出所有大小写字母及数字

    1. 用一行输出所有大(小)写字母,以及数字 print([chr(i) for i in range(65, 91)]) # 所有大写字母 print([chr(i) for i in range( ...

  3. iOS开发之--实现倒计时显示时分秒

    这段时间写公司的一个外包项目,需要用到倒计时:需要显示时分秒,通过在网上搜集资料,找到了2中方法,我把这两种方法结合起来,可以很好的满足这个需求: 1.创建一个类继承自UIlabel,用来展示时分秒的 ...

  4. 【黑金原创教程】【TimeQuest】【第三章】TimeQuest 扫盲文

    声明:本文为黑金动力社区(http://www.heijin.org)原创教程,如需转载请注明出处,谢谢! 黑金动力社区2013年原创教程连载计划: http://www.cnblogs.com/al ...

  5. python练习题集合-1

    author:headsen chen  date : 2018-05-31  17:59:04 notice:本文素材来自于:<< 笨方法学python >> 这本书,由本人 ...

  6. 【BZOJ3555】[Ctsc2014]企鹅QQ hash

    [BZOJ3555][Ctsc2014]企鹅QQ Description PenguinQQ是中国最大.最具影响力的SNS(Social Networking Services)网站,以实名制为基础, ...

  7. nginx的allow和deny配置

    转自:http://www.ttlsa.com/linux/nginx-modules-ngx_http_access_module/ 单看nginx模块名ngx_http_access_module ...

  8. [算法][LeetCode]Single Number——异或运算的巧妙运用

    题目要求 Given an array of integers, every element appears twice except for one. Find that single one. N ...

  9. SaltStack数据系统-Pillar

    上一篇:SaltStack数据系统-Grains 使用saltstack进行配置管理可以使用pillar定义主机假如是Openstack修改了一下nova的密码就需要修改很多配置文件 pillar很安 ...

  10. Exchange Database Status(Copy Status ,Content Index State,QueueLength,Move Status...)

    Copy Status Description Mounted The active copy is online and accepting client connections. Only the ...