/// <summary>
        /// DataRow 转成 模型
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="dr"></param>
        /// <returns></returns>
        public static T ToModel<T>(this DataRow dr) where T : class, new()
        {
            T ob = new T();
            if (dr != null)
            {
                Type vType = typeof(T);
                //创建一个属性的列表
                PropertyInfo[] prlist = vType.GetProperties();                 DataColumnCollection vDataCoulumns = dr.Table.Columns;
                try
                {
                    foreach (PropertyInfo vProInfo in prlist)
                    {
                        if (vDataCoulumns.IndexOf(vProInfo.Name) >= && dr[vProInfo.Name] != DBNull.Value)
                        {
                            vProInfo.SetValue(ob, dr[vProInfo.Name], null);
                        }
                    }
                }
                catch (Exception ex)
                {                 }
            }
            return ob;
        }
        /// <summary>
        /// DataTable 转换为List 集合
        /// </summary>
        /// <typeparam name="T">类型</typeparam>
        /// <param name="dt">DataTable</param>
        /// <returns></returns>
        public static List<T> ToList<T>(this DataTable dt) where T : class, new()
        {
            //创建一个属性的列表
            List<PropertyInfo> prlist = new List<PropertyInfo>();
            //获取TResult的类型实例  反射的入口
            Type t = typeof(T);
            //获得TResult 的所有的Public 属性 并找出TResult属性和DataTable的列名称相同的属性(PropertyInfo) 并加入到属性列表 
            Array.ForEach<PropertyInfo>(t.GetProperties(), p => { if (dt.Columns.IndexOf(p.Name) != -) prlist.Add(p); });
            //创建返回的集合
            List<T> oblist = new List<T>();
            if (dt != null)
            {
                foreach (DataRow row in dt.Rows)
                {
                    try
                    {
                        //创建TResult的实例
                        T ob = new T();
                        //找到对应的数据  并赋值
                        prlist.ForEach(p =>
                        {
                            if (dt.Columns.IndexOf(p.Name) >= && row[p.Name] != DBNull.Value)
                            {
                                try
                                {
                                    //如果是泛型
                                    if (p.PropertyType.ToString().IndexOf("System.Nullable") > -)
                                    {
                                        string types = p.PropertyType.ToString().Substring(p.PropertyType.ToString().IndexOf("[") + );
                                        types = types.Substring(, types.Length - );                                         Type typeinfo = Type.GetType(types);
                                        p.SetValue(ob, Convert.ChangeType(row[p.Name], typeinfo), null);                                     }
                                    else
                                    {
                                        p.SetValue(ob, Convert.ChangeType(row[p.Name], p.PropertyType), null);//类型转换
                                    }
                                }
                                catch (Exception ex)
                                {
                                    LogUtility.WriteLogForExcepiton(ex);
                                }                             }
                        });
                        //放入到返回的集合中.
                        oblist.Add(ob);
                    }
                    catch (Exception ex)
                    {
                    }
                }
            }
            return oblist;
        }     
        /// <summary>
/// DataSet转换为泛型集合
/// </summary>
/// <typeparam name="T">泛型类型</typeparam>
/// <param name="ds">DataSet数据集</param>
/// <param name="tableIndex">待转换数据表索引,默认第0张表</param>
/// <returns>返回泛型集合</returns>
public static IList<T> ToList<T>(this DataSet ds, int tableIndex = )
{ if (ds == null || ds.Tables.Count < ) return null;
if (tableIndex > ds.Tables.Count - )
return null; if (tableIndex < )
tableIndex = ; DataTable dt = ds.Tables[tableIndex]; // 返回值初始化
IList<T> result = new List<T>();
for (int j = ; j < dt.Rows.Count; j++)
{
T _t = (T)Activator.CreateInstance(typeof(T));
PropertyInfo[] propertys = _t.GetType().GetProperties(); foreach (PropertyInfo pi in propertys)
{
for (int i = ; i < dt.Columns.Count; i++)
{ // 属性与字段名称一致的进行赋值
if (pi.Name.Equals(dt.Columns[i].ColumnName))
{ // 数据库NULL值单独处理
if (dt.Rows[j][i] != DBNull.Value)
pi.SetValue(_t, dt.Rows[j][i], null);
else
pi.SetValue(_t, null, null);
break;
}
}
}
result.Add(_t);
}
return result;
} /// <summary>
/// DataSet转换为泛型集合
/// </summary>
/// <typeparam name="T">泛型类型</typeparam>
/// <param name="ds">DataSet数据集</param>
/// <param name="tableName">待转换数据表名称,名称为空时默认第0张表</param>
/// <returns>返回泛型集合</returns>
public static IList<T> ToList<T>(this DataSet ds, string tableName)
{ int _TableIndex = ; if (ds == null || ds.Tables.Count < )
return null; if (string.IsNullOrEmpty(tableName))
return ToList<T>(ds, ); for (int i = ; i < ds.Tables.Count; i++)
{ // 获取Table名称在Tables集合中的索引值
if (ds.Tables[i].TableName.Equals(tableName))
{
_TableIndex = i;
break;
}
}
return ToList<T>(ds, _TableIndex);
}

 

对DataSet,DataRow,DateTable转换成相应的模型的更多相关文章

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

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

  2. 利用泛型和反射,管理配置文件,把Model转换成数据行,并把数据行转换成Model

    利用泛型和反射,管理配置文件,把Model转换成数据行,并把数据行转换成Model   使用场景:网站配置项目,为了便于管理,网站有几个Model类来管理配置文件, 比如ConfigWebsiteMo ...

  3. iOS swift HandyJSON组合Alamofire发起网络请求并转换成模型

    在swift开发中,发起网络请求大部分开发者应该都是使用Alamofire发起的网络请求,至于请求完成后JSON解析这一块有很多解决方案,我们今天这里使用HandyJSON来解析请求返回的数据并转化成 ...

  4. DataSet转换成List<>

    方法一: //DataSet转换成List<ArticleInfo> public List<ArticleInfo> GetArticleList(DataSet ds) { ...

  5. TXT文件转换成DataSet数据集

    /// <summary> /// TXT文件转换成DataSet数据集 /// </summary> /// <param name="FilePath&qu ...

  6. c#将List&lt;T&gt;转换成DataSet

    /// <summary>         /// List<T> 转换成DataSet         /// </summary>         /// &l ...

  7. .net 数据源DataSet 转换成模型

    /// <summary> /// DataSet转换成model 自动赋值返回集合 /// </summary> /// <typeparam name="T ...

  8. DataSet 反射转换成 List<T>

    /// <summary> /// DataSet转换成指定返回类型的实体集合 /// </summary> /// <typeparam name="T&qu ...

  9. 使用linq对ado.net查询出来dataset集合转换成对象(查询出来的数据结构为一对多)

    public async Task<IEnumerable<QuestionAllInfo>> GetAllQuestionByTypeIdAsync(int id) { st ...

随机推荐

  1. incast.tcl

    # Basic Incast Simulation # Check Args if {$argc != 5} { puts "Usage: ns incast <srv_num> ...

  2. java.langThrowable:STACKTRACE

    Jboss版本是4.2.0.GA代码运行完后总报错 但是程序的运行结果没问题 请问下这是什么原因2009-12-11 01:53:26,611 INFO  [org.jboss.resource.co ...

  3. nginx 开启gzip压缩--字符串压缩比率很牛叉

    刚刚给博客加了一个500px相册插件,lightbox引入了很多js文件和css文件,页面一下子看起来非常臃肿,所以还是把Gzip打开了. 环境:Debian 6 1.Vim打开Nginx配置文件 v ...

  4. lua的local问题

    1. 初识 使用Local带来错误.自己写了一个递归的函数,结果报错: local fLocal = function(n) ) then return n; else ) end end )) 错误 ...

  5. Doing Research Needs Efforts

    What is research?   From YouTube Video or baiduyun Links What does not? spend many hours before you ...

  6. 浅谈js冒泡事件2

    js冒泡阻止 1. 事件目标 现在,事件处理程序中的变量event保存着事件对象.而event.target属性保存着发生事件的目标元素.这个属性是DOM API中规定的,但是没有被所有浏览器实现 . ...

  7. Debian/Kali 安装原生Firefox

    出于种种原因,有很多人信仰原装纯净:就像debian下的iceweasel,有人总想换成firefox.好吧,正好最近29版发布了,我们无视掉这两者哥两好的关系,尝试在Debian/Kali 下安装F ...

  8. Shell,Bash,等脚本学习(有区别)

    二元比较操作符,比较变量或者比较数字.注意数字与字符串的区别.   整数比较   -eq        等于,如:if [ "$a" -eq "$b" ] -n ...

  9. 复制collections

    use product-test; var cursor = db.user.find(); use product; while(cursor.hasNext()){db.user.insert(c ...

  10. C#检验IIS版本、SQL Server版本、SilverLight版本

    之前做一个小项目,使用C#检验这些软件的版本,到处找了一些代码,也能作用,记录一下,以防以后用到. 一.检验IIS版本 public static bool checkIIS(string destV ...