DataTable转换成List<T>

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5. using System.Data;  
  6. using System.Collections;  
  7. using System.Reflection;  
  8. namespace DatableToList  
  9. {  
  10.     class ConvertHelper<T> where T : new()  
  11.     {  
  12.         /// <summary>  
  13.         /// 利用反射和泛型  
  14.         /// </summary>  
  15.         /// <param name="dt"></param>  
  16.         /// <returns></returns>  
  17.         public static List<T> ConvertToList(DataTable dt)  
  18.         {  
  19.   
  20.             // 定义集合  
  21.             List<T> ts = new List<T>();  
  22.   
  23.             // 获得此模型的类型  
  24.             Type type = typeof(T);  
  25.             //定义一个临时变量  
  26.             string tempName = string.Empty;  
  27.             //遍历DataTable中所有的数据行  
  28.             foreach (DataRow dr in dt.Rows)  
  29.             {  
  30.                 T t = new T();  
  31.                 // 获得此模型的公共属性  
  32.                 PropertyInfo[] propertys = t.GetType().GetProperties();  
  33.                 //遍历该对象的所有属性  
  34.                 foreach (PropertyInfo pi in propertys)  
  35.                 {  
  36.                     tempName = pi.Name;//将属性名称赋值给临时变量  
  37.                     //检查DataTable是否包含此列(列名==对象的属性名)    
  38.                     if (dt.Columns.Contains(tempName))  
  39.                     {  
  40.                         // 判断此属性是否有Setter  
  41.                         if (!pi.CanWrite) continue;//该属性不可写,直接跳出  
  42.                         //取值  
  43.                         object value = dr[tempName];  
  44.                         //如果非空,则赋给对象的属性  
  45.                         if (value != DBNull.Value)  
  46.                             pi.SetValue(t, value, null);  
  47.                     }  
  48.                 }  
  49.                 //对象添加到泛型集合中  
  50.                 ts.Add(t);  
  51.             }  
  52.   
  53.             return ts;  
  54.   
  55.         }  
  56.     }  
  57. }  
原文地址:https://www.cnblogs.com/bloodyboy/p/3521449.html