C# 将DataTable反射成实体类(高效)

工具类实现(直接复制粘贴) 

    public class DataTableModelConvertHelper
    {

       

        public static List<T> ConvertList<T>(DataTable table) where T : class
        {
            List<ResultArgs<string, string, Type, System.Reflection.PropertyInfo>> lstArgses = new List<ResultArgs<string, string, Type, System.Reflection.PropertyInfo>>();

            var props = typeof(T).GetProperties();

            foreach (var cln in props)//获取实体类的属性及属性类型
            {
                lstArgses.Add(new ResultArgs<string, string, Type, System.Reflection.PropertyInfo>()
                {
                    Value1 = string.Empty,//Table.ColName 数据表列名
                    Value2 = cln.Name,//Entity.Name 实体类属性名
                    Value3 = cln.PropertyType,//Entity.Type 实体类属性类型
                    Value4 = cln
                });
            }


            foreach (DataColumn cln in table.Columns)//获取数据表DataTable的列名
            {
                foreach (var resultArgse in lstArgses)
                {
                    if (resultArgse.Value2.ToLower() == cln.ColumnName.ToLower())//都转换为小写做匹配
                    {
                        resultArgse.Value1 = cln.ColumnName;
                    }
                }
            }

            List<T> lst = new List<T>();
            foreach (DataRow row in table.Rows)
            {
                var info = Activator.CreateInstance<T>();

                foreach (var ocn in lstArgses)
                {
                    if (!string.IsNullOrEmpty(ocn.Value1))
                    {
                        try
                        {
                            //Console.WriteLine("ocn.Value1:{0};ocn.Value2:{1}", ocn.Value1, ocn.Value2);
                            if (ocn.Value4 != null && row[ocn.Value1] != DBNull.Value)
                            {
                                var objValue = DataTableModelConvertHelper.ChangeType(row[ocn.Value1], ocn.Value3);
                                //Console.WriteLine("objValue:{0}", objValue);
                                ocn.Value4.SetValue(info, objValue, null);
                            }
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine(ex.ThrowExceptionDetail());
                        }
                    }
                }
                lst.Add(info);
            }
            return lst;
        }

        #region = ChangeType =
        private static object ChangeType(object obj, Type conversionType)
        {
            return ChangeType(obj, conversionType, Thread.CurrentThread.CurrentCulture);
        }
        private static object ChangeType(object obj, Type conversionType, IFormatProvider provider)
        {
            #region Nullable
            Type nullableType = Nullable.GetUnderlyingType(conversionType);
            if (nullableType != null)
            {
                if (obj == null)
                {
                    return null;
                }
                return Convert.ChangeType(obj, nullableType, provider);
            }
            #endregion
            if (typeof(System.Enum).IsAssignableFrom(conversionType))
            {
                return Enum.Parse(conversionType, obj.ToString());
            }
            return Convert.ChangeType(obj, conversionType, provider);
        }
        #endregion
    }
    public class ResultArgs<T, G>
    {
        public T Value1 { set; get; }
        public G Value2 { set; get; }
    }
    public class ResultArgs<T, G, H>
    {
        public T Value1 { set; get; }
        public G Value2 { set; get; }
        public H Value3 { set; get; }
    }
    public class ResultArgs<T, G, H, J>
    {
        public T Value1 { set; get; }
        public G Value2 { set; get; }
        public H Value3 { set; get; }
        public J Value4 { set; get; }
    }

 调用方式

//RequestInfo是实体类
//table是Datatable
//将DataTable表格数据转换为Model实体类代码
var lst = DataTableModelConvertHelper.ConvertList<RequestInfo>(table);

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
可以使用反射来实现将 DataTable 转换为实体类。 首先,需要定义一个实体类,该类的属性应该与 DataTable 的列名相同。 接下来,可以编写一个方法,该方法接受一个 DataTable 作为参数,并使用反射来将 DataTable 的数据转换为实体类的对象列表。具体实现方法如下: ```csharp public static List<T> ConvertDataTableToList<T>(DataTable dt) where T : class, new() { List<T> list = new List<T>(); Type type = typeof(T); PropertyInfo[] properties = type.GetProperties(); foreach (DataRow row in dt.Rows) { T obj = new T(); foreach (PropertyInfo property in properties) { if (dt.Columns.Contains(property.Name)) { if (row[property.Name] != DBNull.Value) { property.SetValue(obj, row[property.Name], null); } } } list.Add(obj); } return list; } ``` 这个方法使用泛型参数 T 来指定要转换的实体类类型,并使用 typeof(T) 来获取该类型的 Type 对象。然后,使用 GetProperties() 方法获取该类型的所有属性信息。 在循环遍历 DataTable 的每一行时,创建一个新的实体类对象,并逐个遍历属性信息,使用 SetValue() 方法将 DataTable 的对应列值赋值给实体类对象的属性。 最后,将所有实体类对象添加到列表中,并返回该列表。 使用方法示例: ```csharp DataTable dt = new DataTable(); // 填充DataTable List<MyClass> list = ConvertDataTableToList<MyClass>(dt); ``` 其中,MyClass 表示要转换的实体类类型。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值