C#DataTable转list

来源:互联网 发布:无法连接到windows 编辑:程序博客网 时间:2024/06/03 21:17


    把查询结果以Datatable返回很方便,但是在检索数据时又很麻烦,没有模型类型检索方便。

所以很多人都是按照以下的方式做的:

//获得查询结果Datatable dt=sqlhelper.ExecuteQuery(...);//把Datatable转换为List<UserInfo>List<UserInfo> users=ConvertToUserInfo(dt);
    问题:如果系统中有几十个上百个模型,那不是每个模型中都要写个DataTable转换为此模型的方法吗?

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

using System;using System.Collections.Generic;using System.Text;using System.Data;using System.Reflection;namespace DAL   {        /// <summary>        /// 实体转换辅助类        /// </summary>        public class DatatableToList        {            public static List<T> ConvertToList<T>(DataTable dt)where T:new()            {                // 定义集合                 List<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 = sqlhelper.ExecuteQuery(...);  // 把DataTable转换为List<UserInfo>  return DatatableToList.ConvertToList<UserInfo>(dt);


原创粉丝点击