DataSet结果转模型类

引入命名空间:

using System.Data;
using System.Reflection;

类封装代码:

    public class ModelHelper
    {
        public T To<T>(DataRow dr) where T : new()
        {
            T model= new T();                   //T model = default(T); //model = Activator.CreateInstance<T>();
            Type t = model.GetType();                       //获取模型类的类型

            //循环遍历模型类的每一个属性,并为其赋值
            foreach (PropertyInfo pi in t.GetProperties())
            {
                if (dr.Table.Columns.Contains(pi.Name))           //如果DataTable的列中包含当前的属性名
                {
                    if (!pi.CanWrite) continue;
                    object value = dr[pi.Name];
                    if (value != DBNull.Value)
                    {
                        pi.SetValue(model, value, null);
                    }
                    else
                    {
                        pi.SetValue(model, null, null);
                    }
                }

            }

            return model;
        }

        public IList<T> ToList<T>(DataTable dt) where T : new()
        {
            List<T> list = new List<T>();
            foreach (DataRow dr in dt.Rows)
            {
                list.Add(To<T>(dr));
            }
            return list;
        }


        //另一种写法
        //public T To<T>(DataTable dt) where T : new()
        //{
        //    T model = default(T);
        //    model = Activator.CreateInstance<T>();

        //    PropertyInfo[] propertys = model.GetType().GetProperties();         //获取模型类的类型

        //    //循环遍历模型类的每一个属性,并为其赋值
        //    foreach (PropertyInfo pi in propertys)
        //    {
        //        if (dt.Columns.Contains(pi.Name))           //如果DataTable的列中包含当前的属性名
        //        {
        //            if (!pi.CanWrite) continue;
        //            object value = dt.Rows[0][pi.Name];
        //            if (value != DBNull.Value)
        //            {
        //                pi.SetValue(model, value, null);
        //            }
        //            else
        //            {
        //                pi.SetValue(model, null, null);
        //            }
        //        }
        //    }

        //    return model;
        //}
    }
原文地址:https://www.cnblogs.com/zhangchaoran/p/8513430.html