把数据库中取出的DataTable转换成一个对象 或者对象列表

        public static void SetTValue<T>(T model, DataTable dt)
        {
            if (dt.Rows.Count == 0)
            {
                return;
            }
            Type type = typeof(T);
            DataRow dr = dt.Rows[0];
            foreach (DataColumn dc in dt.Columns)
            {
                PropertyInfo pi = type.GetProperty(dc.ColumnName);
                if (pi == null)
                {
                    continue;
                }

                if (dr[dc.ColumnName] != DBNull.Value)
                {
                    pi.SetValue(model, dr[dc.ColumnName], null);
                }
            }
        }
        public static List<T> SetTListValue<T>(DataTable dt) where T : new()
        {
            if (dt.Rows.Count == 0)
            {
                return null;
            }
            List<T> TList = new List<T>();
            Type type = typeof(T);
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                T t = new T();
                DataRow dr = dt.Rows[i];
                foreach (DataColumn dc in dt.Columns)
                {
                    PropertyInfo pi = type.GetProperty(dc.ColumnName);
                    if (pi == null)
                    {
                        continue;
                    }
                    if (dr[dc.ColumnName] != DBNull.Value)
                    {
                        pi.SetValue(t, dr[dc.ColumnName], null);
                    }
                }
                TList.Add(t);
            }
            return TList;
        }
原文地址:https://www.cnblogs.com/sherlock99/p/3680549.html