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);

 

上一篇:DataTable 表生成代码(zml)


下一篇:C#丨为DataGridView控件绑定数据源