DataTable 和List之间相互转换的方法


1、list 转化DateTable

public static DataTable ToDataTable(IEnumerable collection)
 {      var props = typeof(T).GetProperties();      var dt = new DataTable();      dt.Columns.AddRange(props.Select(p => new DataColumn(p.Name, p.PropertyType)).ToArray());      if (collection.Count() > 0)      {          for (int i = 0; i < collection.Count(); i++)          {              ArrayList tempList = new ArrayList();              foreach (PropertyInfo pi in props)              {                  object obj = pi.GetValue(collection.ElementAt(i), null);                  tempList.Add(obj);              }              object[] array = tempList.ToArray();              dt.LoadDataRow(array, true);          }      }      return dt;  } //博主比较笨,有些程序集中的方法不熟悉,记录一下说明!!!!   typeof(T):初始化系统的新实例。类型类。 GetProperties();返回当前系统的所有公共属性。类型 Select:将序列中的每个元素投影到新形式中。 AddRange():复制指定系统的元素。数据数据列数组的末尾 Content:获取属于此表的列的集合。 ElementAt:返回指定索引中的元素 GetValue:返回具有可选索引值的指定对象的属性值 LoadDataRow:查找并更新特定行。如果没有找到匹配的行,将创建新行

 1、DateTable转化list (封装的通用类)

using System;      
using System.Collections.Generic;  
using System.Text;    
using System.Data;    
using System.Reflection;  
namespace NCL.Data    
{    
    ///     
    /// 实体转换辅助类    
    ///     
    public class ModelConvertHelper where   T : new()    
     {    
        public static IList ConvertToModel(DataTable dt)    
         {    
            // 定义集合    
             IList ts = new List(); 
     
            // 获得此模型的类型   
             Type type = typeof(T);      
            string tempName = "";      
      
            foreach (DataRow dr in dt.Rows)      
             {    
                 T t = new T();     
                // 获得此模型的公共属性      
                 PropertyInfo[] propertys = t.GetType().GetProperties(); 
                foreach (PropertyInfo pi in propertys)      
                 {      
                     tempName = pi.Name;  // 检查DataTable是否包含此列    
   
                    if (dt.Columns.Contains(tempName))      
                     {      
                        // 判断此属性是否有Setter      
                        if (!pi.CanWrite) continue;         
   
                        object value = dr[tempName];      
                        if (value != DBNull.Value)      
                             pi.SetValue(t, value, null);  
                     }     
                 }      
                 ts.Add(t);      
             }     
            return ts;     
         }     
     }    
}