编程语言
首页 > 编程语言> > C# 反射实现DataTable转ModelList

C# 反射实现DataTable转ModelList

作者:互联网

1.需要引入命名空间 using System.Reflection;

    /// <summary>
    /// 实体转换辅助类
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public class ModelConvertHelper<T> where T : new()//泛型约束 无参构造函数
    {
        /// <summary>
        /// DataTable 转 ModelList
        /// </summary>
        /// <param name="dataTable"></param>
        /// <returns></returns>
        public static List<T> ConvertToModel(DataTable dataTable)
        {
            List<T> ts = new List<T>();
            foreach (DataRow dataRow in dataTable.Rows)
            {
                T t = new T();
                Type type = t.GetType();
                string tempName = string.Empty;
                int Count = dataTable.Columns.Count;//总列数
                int Index = 1;
                if (Index > Count)
                {
                    ts.Add(t);
                    continue;
                }
                //反射获取所有属性
                foreach (PropertyInfo propertie in type.GetProperties())
                {
                    tempName = propertie.Name;
                    if (dataTable.Columns.Contains(tempName.ToUpper()))//如果包含此列
                    {
                        object value = dataRow[tempName];
                        if (value != null)
                        {
                            propertie.SetValue(t, value);//属性赋值
                        }
                    }
                    Index++;
                }
                ts.Add(t);
            }
            return ts;
        }
    }

调用方法:

            var dataList = ModelConvertHelper<ConfigureViewModel>.ConvertToModel(dataTable);

 

标签:Index,propertie,C#,ModelList,ts,value,dataTable,DataTable,tempName
来源: https://www.cnblogs.com/dony-dong/p/14419507.html