当前位置: 首页 > news >正文

将DataTable转换成类的方法

/// <summary>

    /// 使用类的属性名对应DataTable中的字段名

    /// </summary>

    public static class TableToModel

    {

        /// <summary>

        /// DataRow扩展方法:将DataRow类型转化为指定类型的实体

        /// </summary>

        /// <typeparam name="T">实体类型</typeparam>

        /// <returns></returns>

        public static T ToModel<T>(this DataRow dr) where T : class, new()

        {

            return ToModel<T>(dr, true);

        }

        /// <summary>

        /// 将DataRow类型转化为指定类型的实体

        /// </summary>

        /// <typeparam name="T">实体类型</typeparam>

        /// <param name="dateTimeToString">是否需要将日期转换为字符串,默认为转换,值为true</param>

        /// <returns></returns>

        /// <summary>

        public static T ToModel<T>(this DataRow dr, bool dateTimeToString) where T : class, new()

        {

            if (dr != null)

                return ToList<T>(dr.Table, dateTimeToString).First();

 

            return null;

        }

 

        /// <summary>

        /// 将DataTable类型转化为指定类型的实体集合

        /// </summary>

        /// <typeparam name="T">实体类型</typeparam>

        /// <returns></returns>

        public static List<T> ToList<T>(this DataTable dt) where T : class, new()

        {

            return ToList<T>(dt, true);

        }

 

        /// <summary>

        ///将DataTable类型转化为指定类型的实体集合

        /// </summary>

        /// <typeparam name="T">实体类型</typeparam>

        /// <param name="dateTimeToString">是否需要将日期转换为字符串,默认为转换,值为true</param>

        /// <returns></returns>

        public static List<T> ToList<T>(this DataTable dt, bool dateTimeToString) where T : class, new()

        {

            List<T> list = new List<T>();

 

            if (dt != null)

            {

                List<PropertyInfo> infos = new List<PropertyInfo>();

 

                Array.ForEach<PropertyInfo>(typeof(T).GetProperties(), p =>

                {

                    if (dt.Columns.Contains(p.Name) == true)

                    {

                        infos.Add(p);

                    }

                });

 

                SetList<T>(list, infos, dt, dateTimeToString);

            }

 

            return list;

        }

 

        #region 私有方法

 

        private static void SetList<T>(List<T> list, List<PropertyInfo> infos, DataTable dt, bool dateTimeToString) where T : class, new()

        {

            foreach (DataRow dr in dt.Rows)

            {

                T model = new T();

 

                infos.ForEach(p =>

                {

                    if (dr[p.Name] != DBNull.Value)

                    {

                        object tempValue = dr[p.Name];

                        if (dr[p.Name].GetType() == typeof(DateTime) && dateTimeToString == true)

                        {

                            tempValue = dr[p.Name].ToString();

                        }

                        try

                        {

                            p.SetValue(model, tempValue, null);

                        }

                        catch { }

                    }

                });

                list.Add(model);

            }

        }

 

        #endregion

}

 

/// <summary>

    /// 使用类的属性的Description属性对应DataTable中的字段名

    /// </summary>

    public static class TableToModel

    {

        /// <summary>

        /// 将DataRow类型转化为指定类型的实体

        /// </summary>

        /// <typeparam name="T">实体类型</typeparam>

        /// <returns></returns>

        public static T ToModel<T>(this DataRow dr) where T : class, new()

        {

            return ToModel<T>(dr, true);

        }

        /// <summary>

        /// 将DataRow类型转化为指定类型的实体

        /// </summary>

        /// <typeparam name="T">实体类型</typeparam>

        /// <param name="dateTimeToString">是否需要将日期转换为字符串,默认为转换,值为true</param>

        /// <returns></returns>

        /// <summary>

        public static T ToModel<T>(this DataRow dr, bool dateTimeToString) where T : class, new()

        {

            if (dr != null)

                return ToList<T>(dr.Table, dateTimeToString).First();

 

            return null;

        }

 

        /// <summary>

        ///将DataTable类型转化为指定类型的实体集合

        /// </summary>

        /// <typeparam name="T">实体类型</typeparam>

        /// <returns></returns>

        public static List<T> ToList<T>(this DataTable dt) where T : class, new()

        {

            return ToList<T>(dt, true);

        }

 

        /// <summary>

        /// 将DataTable类型转化为指定类型的实体集合

        /// </summary>

        /// <typeparam name="T">实体类型</typeparam>

        /// <param name="dateTimeToString">是否需要将日期转换为字符串,默认为转换,值为true</param>

        /// <returns></returns>

        public static List<T> ToList<T>(this DataTable dt, bool dateTimeToString) where T : class, new()

        {

            List<T> list = new List<T>();

 

            if (dt != null)

            {

                List<PropertyInfo> infos = new List<PropertyInfo>();

 

                Array.ForEach<PropertyInfo>(typeof(T).GetProperties(), p =>

                {

                    foreach (Attribute att in p.GetCustomAttributes(true))

                    {

                        System.ComponentModel.DescriptionAttribute dscript = att as System.ComponentModel.DescriptionAttribute;

                        if (dscript != null)

                        {

                            if (dt.Columns.Contains(dscript.Description) == true)

                            {

                                infos.Add(p);

                            }

                        }

                    }

 

                });

 

                SetList<T>(list, infos, dt, dateTimeToString);

            }

 

            return list;

        }

 

        #region 私有方法

 

        private static void SetList<T>(List<T> list, List<PropertyInfo> infos, DataTable dt, bool dateTimeToString) where T : class, new()

        {

            foreach (DataRow dr in dt.Rows)

            {

                T model = new T();

 

                infos.ForEach(p =>

                {

                    foreach (Attribute att in p.GetCustomAttributes(true))

                    {

                        System.ComponentModel.DescriptionAttribute dscript = att as System.ComponentModel.DescriptionAttribute;

                        if (dscript != null)

                        {

                            if (dr[dscript.Description] != DBNull.Value)

                            {

                                object tempValue = dr[dscript.Description];

                                if (dr[dscript.Description].GetType() == typeof(DateTime) && dateTimeToString == true)

                                {

                                    tempValue = dr[p.Name].ToString();

                                }

                                try

                                {

                                    p.SetValue(model, tempValue, null);

                                }

                                catch { }

                            }

                        }

                    }

                });

                list.Add(model);

            }

        }

 

        #endregion

    }

转载于:https://www.cnblogs.com/TNTZWC/archive/2010/11/25/1887299.html

相关文章:

  • NOKIA C5-00怎么连接电脑??
  • 2010 支付宝DevDiv移动开发者大会[上海]
  • Java王者归来 6月Tiobe编程语言排行榜公布
  • 关于 在JQuery dialog里的服务器控件 事件失效问题
  • jquery的uploadify在 firefox 上传出问题,怎么解决啊
  • 从客户端(TexContent=rty内容)中检测到有潜在危险的Request.Form 值 解决方案
  • Linux--打包压缩 tar,gzip,bzip2
  • DataRow的RowState属性
  • HTML a 标签的 target 属性说明
  • 冬季谨防胃病复发 放松精神吃温热食物
  • 最经典的权限设计同样也是最糟糕的权限设计,权限设计理念最关键第一步之间的PK...
  • 回到达姆喽
  • 2011年通信运营的十大悬念
  • 改造面向过程式设计
  • 朝三暮四,还是朝四暮三?
  • JavaScript-如何实现克隆(clone)函数
  • 3.7、@ResponseBody 和 @RestController
  • Android交互
  • Apache的80端口被占用以及访问时报错403
  • Codepen 每日精选(2018-3-25)
  • Cookie 在前端中的实践
  • Docker 笔记(2):Dockerfile
  • Java 内存分配及垃圾回收机制初探
  • Java基本数据类型之Number
  • js 实现textarea输入字数提示
  • JS实现简单的MVC模式开发小游戏
  • OSS Web直传 (文件图片)
  • PHP那些事儿
  • 动手做个聊天室,前端工程师百无聊赖的人生
  • 动态规划入门(以爬楼梯为例)
  • 更好理解的面向对象的Javascript 1 —— 动态类型和多态
  • 技术发展面试
  • 聊聊hikari连接池的leakDetectionThreshold
  • 少走弯路,给Java 1~5 年程序员的建议
  • 线上 python http server profile 实践
  • 追踪解析 FutureTask 源码
  • 阿里云ACE认证学习知识点梳理
  • !! 2.对十份论文和报告中的关于OpenCV和Android NDK开发的总结
  • #HarmonyOS:基础语法
  • #经典论文 异质山坡的物理模型 2 有效导水率
  • (C语言)共用体union的用法举例
  • (delphi11最新学习资料) Object Pascal 学习笔记---第2章第五节(日期和时间)
  • (javascript)再说document.body.scrollTop的使用问题
  • (附源码)spring boot基于Java的电影院售票与管理系统毕业设计 011449
  • (附源码)springboot高校宿舍交电费系统 毕业设计031552
  • (附源码)计算机毕业设计SSM智能化管理的仓库管理
  • (离散数学)逻辑连接词
  • (十五)devops持续集成开发——jenkins流水线构建策略配置及触发器的使用
  • (一)Dubbo快速入门、介绍、使用
  • (原創) 如何刪除Windows Live Writer留在本機的文章? (Web) (Windows Live Writer)
  • (转)创业的注意事项
  • (转)大型网站的系统架构
  • (转载)hibernate缓存
  • (转载)OpenStack Hacker养成指南
  • . Flume面试题