Datatable与实体list之间的转换

本文介绍了一个C#公共静态类,用于实现将DataTable转换为List和将List转换为DataTable的功能。通过获取模型的公共属性,并在两个过程中进行数据的双向映射。

public static class ConvertDataTableWithList<T> where T:new()
    {
        public static List<T> ConvertToModelList(DataTable dt)
        {
            //定义集合
            List<T> ts = new List<T>();
            T t = new T();
            //获取此模型的公共属性
            PropertyInfo[] propertys = t.GetType().GetProperties();
            foreach (DataRow row in dt.Rows)
            {
                t = new T();
                foreach (PropertyInfo pi in propertys)
                {
                    //检查DataTable是否包含此列
                    if (dt.Columns.Contains(pi.Name))
                    {
                        //判断此属性是否有set
                        if (!pi.CanWrite)
                            continue;
                        object value = row[pi.Name];
                        if (value != DBNull.Value)
                            pi.SetValue(t, value, null);
                    }
                }
                ts.Add(t);
            }
            return ts;
        }
        public static DataTable ConvertToDataTable(List<T> list)
        {
            DataTable dt=new DataTable();
           
            T t=new T();
            PropertyInfo [] propertys=t.GetType().GetProperties();
            //给datatable添加列
            foreach (PropertyInfo pi in propertys)
            {
                dt.Columns.Add(pi.Name);
            }
            dt.AcceptChanges();
            foreach (T item in list)
            {
                t = new T();
                DataRow dr = dt.NewRow();
                foreach (PropertyInfo pi in propertys)
                {
                    if (!pi.CanWrite)
                        continue;
                    dr[pi.Name] = pi.GetValue(t);
                }
                dt.Rows.Add(dr);
            }
            dt.AcceptChanges();
            return dt;
        }
    }

转载于:https://www.cnblogs.com/lvdong-1986/p/4257748.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值