C# DataTable转换List类

博客介绍了封装成类的代码,类名为CovertListHelper,并提及如何使用。作者在昭哥帮助下学习该内容,起初不会,经摸索学习发现其好用,鼓励小伙伴尝试使用。

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

封装成类的代码:


类名为CovertListHelper`

using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace DAL
{
    public class CovertListHelper
    {
        public List<T> convertToList<T>(DataTable dt) where T : new()
        {
            //定义集合
            List<T> ts = new List<T>();
            //获得此模型的类型
            Type type = typeof(T);
            //定义一个临时的变量
            string tempName = "";
            //遍历datatable中所有数据行
            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,这个啥意思呢,就是我们的实体层的{get;set;}如果我们的实体有了set方法,就说明可以赋值!
                        if (!pi.CanWrite) continue;
                        {
                            //取值  
                            object value = dr[tempName];
                            if (value != DBNull.Value)
                                pi.SetValue(t, value, null);
                        }
                    }
                }
                //对象添加到泛型集合中
                ts.Add(t);
            }
            return ts;
        }
    }
}

如何使用?

 

//实例化这个类
DAL.CovertListHelper tolist = new CovertListHelper();
//把DataTable转换为List
//要转换成的List类型为:UserEntity
//需要转换的DataTable为:table
List<UserEntity> list = tolist.convertToList<UserEntity>(table);

 

个人感悟:在昭哥的帮助下,学习了这个,但是一开始还是不会,但是通过不断的摸索,不断的学习,发现这个真的很好用,希望小伙伴们可以尝试去使用一下。

评论 25
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值