C# 用Linq实现DataTable转换成List

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/iBenxiaohai123/article/details/88056968
public static List<User> ConvertDataTableToObjectList(DataTable dt)
{
      var list = (from t in dt.AsEnumerable()
                  select (new User
                  {
                    /*注意:t.Field<int>("Id")中的int表示DataTable中的数据类型,Id表示对应的列
                     * t.Field<int>("Id")表示把DataTable中的列名为Id的列对应的值赋给User的Id属性,
                     * 如果你不确定Field的数据类型,你可以用断点来查看
                    */
                    Id = t.Field<int>("Id"),
                    Name = t.Field<string>("Name"),
                    Email = t.Field<string>("Email"),
                    Age = t.Field<int>("Age"),
                  })).OrderBy(x => Guid.NewGuid().ToString()).ToList();
      return list;
 }

问题:如果系统有几十上百个模型,那不是每个模型中都要写个把DataTable转换为此模型的方法吗?  

解决:能不能写个通用类,可以把DataTable转换为任何模型,呵呵,这就需要利用反射和泛型了

using System;      
using System.Collections.Generic;  
using System.Text;    
using System.Data;    
using System.Reflection;  
namespace NCL.Data    
{    
    /// <summary>    
    /// 实体转换辅助类    
    /// </summary>    
    public class ModelConvertHelper<T> where   T : new()    
     {    
        public static IList<T> ConvertToModel(DataTable dt)    
         {    
            // 定义集合    
             IList<T> ts = new List<T>(); 
     
            // 获得此模型的类型   
             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;     
         }     
     }    
}

使用方式

// 获得查询结果  
DataTable dt = DbHelper.ExecuteDataTable(...);  
// 把DataTable转换为IList<UserInfo>  
IList<UserInfo> users = ModelConvertHelper<UserInfo>.ConvertToModel(dt);

猜你喜欢

转载自blog.csdn.net/iBenxiaohai123/article/details/88056968