本案例提供了:把DataRow转换为单个实体、dataTable转换为List泛型支持时间格式转换。

下文的方法都是扩展方法。扩展方法要求写在静态类中,方法也要静态。

  • 它必须在一个非嵌套、非泛型的静态类中
  • 它至少要有一个参数
  • 第一个参数必须加上this关键字作为前缀(第一个参数类型也称为扩展类型,即指方法对这个类型进行扩展)
  • 第一个参数不能用其他任何修饰符(如不能使用ref out等修饰符)
  • 第一个参数的类型不能是指针类型

1.将DataRow转换为实体

     /// <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);
        }

2.将DataRow转换为实体可设置时间格式转换

        /// <summary>
        /// DataRow扩展方法:将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;
        }    

3.将DataTable转换为实体

       /// <summary>
        /// DataTable扩展方法:将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;
        }    

4.转换实现代码

  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);
            }//结束循环
        }
本文属于转载,感谢原作者的辛勤劳动

 

C#中DataTable与实体集合通用转换(使用扩展方法)的更多相关文章

  1. DataTable与实体类的转换

    多年前写的DataTable与实体类的转换,已放github 阅读目录 介绍 起因 代码 UnitTest GitHub 介绍 很多年前一直使用Ado.net,后来慢慢转型到其他的orm,在转型过程中 ...

  2. Table转换成实体、Table转换成实体集合(可转换成对象和值类型)

    /// <summary> /// Table转换成实体 /// </summary> /// <typeparam name="T">< ...

  3. 生成二维码 加密解密类 TABLE转换成实体、TABLE转换成实体集合(可转换成对象和值类型) COOKIE帮助类 数据类型转换 截取字符串 根据IP获取地点 生成随机字符 UNIX时间转换为DATETIME\DATETIME转换为UNIXTIME 是否包含中文 生成秘钥方式之一 计算某一年 某一周 的起始时间和结束时间

    生成二维码 /// <summary>/// 生成二维码/// </summary>public static class QRcodeUtils{private static ...

  4. DataTable与实体类互相转换

    /// <summary> /// DataTable与实体类互相转换 /// </summary> /// <typeparam name="T"& ...

  5. 【转】DataTable与实体类互相转换

    原文地址:https://www.cnblogs.com/marblemm/p/7084797.html /// <summary> /// DataTable与实体类互相转换 /// & ...

  6. EF Core中如何通过实体集合属性删除从表的数据

    假设在数据库中有两个表:Person表和Book表,Person和Book是一对多关系 Person表数据: Book表数据: 可以看到数据库Book表中所有的数据都属于Person表中"F ...

  7. .NET/C#中对自定义对象集合进行自定义排序的方法

    一个集合可否排序,要看系统知不知道排序的规则,像内建的系统类型,int ,string,short,decimal这些,系统知道怎么排序,而如果一个集合里面放置的是自定义类型,比如自己定义了一个Car ...

  8. C#中的自动属性、隐式类型var、对象初始化器与集合初始化器、扩展方法

    1.自动属性(Auto-Implemented Properties) //以前的写法 .net2.0 private string _userName; public string UserName ...

  9. C#高级知识点概要(3) - 特性、自动属性、对象集合初始化器、扩展方法、Lambda表达式和Linq查询

    1.特性(Attributes) 特性(Attributes),MSDN的定义是:公共语言运行时允许你添加类似关键字的描述声明,叫做attributes, 它对程序中的元素进行标注,如类型.字段.方法 ...

随机推荐

  1. CF Soldier and Badges (贪心)

    Soldier and Badges time limit per test 3 seconds memory limit per test 256 megabytes input standard ...

  2. Javascript -- toFixed()函数

    Javascript——toFiexed()函数 1. toFixed(n) 限制小数点后位数,四舍五入.n:0~20 . 2. 作用对象必须是number,不能为其他类型.如(8.001).toFi ...

  3. linux和Windows下文本格式转换

    1.安装转换工具:sudo apt-get install tofrodos 2.开始转换:fromdos grade.sh

  4. VB.NET 小程序 1

    Public Class Form1 Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click ...

  5. C# 文件相关操作

    百度搜的,下面这个写的挺全的.   FROM Pegasus923 http://www.cnblogs.com/pegasus923/archive/2011/01/26/1944838.html ...

  6. sql获取exec('')的返回值

    ) ) select @sql=('select @a=cNumber+1 from VoucherHistory where CardNumber='''+@CardNumber+'''') exe ...

  7. 微信内置浏览器中,点击下拉框出现页面乱跳转现象(iphone)

    微信内置浏览器中,点击下拉框出现页面乱跳转现象(iphone) 前言: 这是小菜博客的第三篇文章.一直认为自己可以表达的东西太过简单,难以上台面,总是吝啬地不肯写.就算是写,也不知道从何开始.在同事的 ...

  8. css reset及部分layout样式

    /*! normalize.css v3.0.3 | MIT License | github.com/necolas/normalize.css */html { font-family: sans ...

  9. table-layout:fixed 属性的解说

    table-layout:fixed 属性的解说如果想要一个table固定大小,里面的文字强制换行(尤其是在一长串英文文本,并且中间无空格分隔的情况下),以达到使过长的文字不撑破表格的目的,一般是使用 ...

  10. C#自定义时间显示格式

    string time = System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"); 下面是常见的一些日期时间显示格式 标准的For ...