【C# DataTable 扩展类 转对象】

本文介绍了一种将DataRow转换为指定类型的对象的方法,并提供了将整个DataTable转换为List<T>的实用函数。这些方法简化了从数据库读取的数据到业务对象的映射过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


        /// <summary>
        ///   DataRow 转 Obj
        /// </summary>
        /// <typeparam name="T"> </typeparam>
        /// <param name="Dt"></param>
        /// <param name="index">行号</param>
        /// <returns></returns>
        public static T RowToObj<T>(this DataTable Dt ,int  index)
        {
            
            Type t = typeof(T);   // 获取类型
            
                T obj = (T)Activator.CreateInstance(t);  //创建对象
               PropertyInfo[] ProInfo=t.GetProperties();  //获取所属性
                foreach (PropertyInfo p in ProInfo)       // 遍列所有属性
                {
                    string pName = p.Name;                
                    if (!Dt.Columns.Contains(pName)) continue;    // 如果 table里没有这个属性返回 
                if (p.PropertyType == typeof(DateTime) && Convert.ToDateTime(Dt.Rows[index][pName]) < Convert.ToDateTime("1753-01-02")) continue;   //判断 日期类型
                  
                if (Dt.Rows[index][pName] == DBNull.Value) continue;  //如果dt的值为空 返回
                    object pValue = Dt.Rows[index][pName];
                    Type property_type = p.PropertyType;            //获取类型
                    object value = Convert.ChangeType(obj, property_type);  //强制转换类型

                    p.SetValue(value, pValue); 

                }


            return obj;  //返回对象

        }

/// <summary>
        ///  Table 转 List<T>
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="Dt"></param>
        /// <returns></returns>
        public static List<T> TableToObj<T>(this  DataTable Dt) 
        {
            List<T> Ls = new List<T>(); 
            for (int i = 0; i < Dt.Rows.Count; i++)
            {
                T obj = Dt.RowToObj<T>(i);   // 调用 dataRow To Obj
                Ls.Add(obj); 
            }
             

            return Ls;
        
        }

使用方式

 dt.TableToObj<T>();

 dt.RowToObj<T>();

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值