DataTable转换为List<Model>的通用方法

本文介绍了一种将DataTable转换为泛型List&lt;Model&gt;的方法。该方法通过反射机制获取目标类型的属性,并从DataTable中读取相应列的数据来填充这些属性。

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

        /// <summary>
        /// DataTable转换为List<Model>的通用方法 
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="dt"></param>
        /// <returns></returns>
        public static IList<T> DT2Model<T>(DataTable dt) where T : new()
        {
            IList<T> result = new List<T>();
            Type type = typeof(T);
            string tempName = "";

            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
                        if (!pi.CanWrite) continue;

                        object value = dr[tempName];

                        if (value != DBNull.Value)
                            pi.SetValue(t, value, null);
                    }
                }

                result.Add(t);
            }

            return result;
        }

好的,我可以回答你的问题。利用反射可以实现 DataTableList<T> 之间的转换。 首先,我们需要定义一个通用方法,该方法可以将 List<T> 转换DataTable,也可以将 DataTable 转换List<T>。该方法的实现需要借助反射机制。 下面是将 List<T> 转换DataTable 的代码: ```csharp public static DataTable ConvertToDataTable<T>(List<T> list) { DataTable table = new DataTable(); PropertyInfo[] properties = typeof(T).GetProperties(); foreach (PropertyInfo property in properties) { table.Columns.Add(property.Name, property.PropertyType); } foreach (T item in list) { DataRow row = table.NewRow(); foreach (PropertyInfo property in properties) { row[property.Name] = property.GetValue(item, null); } table.Rows.Add(row); } return table; } ``` 上面的代码中,我们首先使用反射机制获取类型 T 的所有属性信息,然后使用这些属性信息创建 DataTable 的列。接着,我们遍历 List<T> 中的每个元素,使用反射获取元素的属性值,并将这些属性值添加到 DataRow 中,最后将 DataRow 添加到 DataTable 中。 下面是将 DataTable 转换List<T> 的代码: ```csharp public static List<T> ConvertToList<T>(DataTable table) where T : new() { List<T> list = new List<T>(); PropertyInfo[] properties = typeof(T).GetProperties(); foreach (DataRow row in table.Rows) { T item = new T(); foreach (PropertyInfo property in properties) { if (table.Columns.Contains(property.Name)) { property.SetValue(item, row[property.Name], null); } } list.Add(item); } return list; } ``` 上面的代码中,我们同样使用反射机制获取类型 T 的所有属性信息,然后遍历 DataTable 中的每个 DataRow,使用反射设置每个 DataRow 中对应的属性值,并将 T 对象添加到 List<T> 中。 希望这些代码可以帮助你解决问题。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值