天天看點

DataSet轉換為泛型集合和DataRow 轉成 模型類

public static class TransformToList
    {
        /// <summary>         
        /// DataSet轉換為泛型集合         
        /// </summary>         
        /// <typeparam name="T">泛型類型</typeparam>         
        /// <param name="ds">DataSet資料集</param>         
        /// <param name="tableIndex">待轉換資料表索引,預設第0張表</param>         
        /// <returns>傳回泛型集合</returns>         
        public static List<T> ToList<T>(this DataSet ds, int tableIndex = 0)
        {

            if (ds == null || ds.Tables.Count < 0) return null;
            if (tableIndex > ds.Tables.Count - 1)
                return null;

            if (tableIndex < 0)
                tableIndex = 0;

            DataTable dt = ds.Tables[tableIndex];

            // 傳回值初始化             
            List<T> result = new List<T>();
            for (int j = 0; j < dt.Rows.Count; j++)
            {
                T _t = (T)Activator.CreateInstance(typeof(T));
                PropertyInfo[] propertys = _t.GetType().GetProperties();

                foreach (PropertyInfo pi in propertys)
                {
                    for (int i = 0; i < dt.Columns.Count; i++)
                    {

                        // 屬性與字段名稱一緻的進行指派                         
                        if (pi.Name.Equals(dt.Columns[i].ColumnName))
                        {

                            // 資料庫NULL值單獨處理                             
                            if (dt.Rows[j][i] != DBNull.Value)
                                pi.SetValue(_t, dt.Rows[j][i], null);
                            else
                                pi.SetValue(_t, null, null);
                            break;
                        }
                    }
                }
                result.Add(_t);
            }
            return result;
        }


        /// <summary>
        /// DataRow 轉成 模型
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="dr"></param>
        /// <returns></returns>
        public static T ToModel<T>(this DataRow dr) where T : class, new()
        {
            T ob = new T();
            if (dr != null)
            {
                Type vType = typeof(T);
                //建立一個屬性的清單
                PropertyInfo[] prlist = vType.GetProperties();


                DataColumnCollection vDataCoulumns = dr.Table.Columns;
                try
                {
                    foreach (PropertyInfo vProInfo in prlist)
                    {
                        if (vDataCoulumns.IndexOf(vProInfo.Name) >= 0 && dr[vProInfo.Name] != DBNull.Value)
                        {
                            vProInfo.SetValue(ob, dr[vProInfo.Name], null);
                        }
                    }
                }
                catch (Exception ex)
                {


                }
            }
            return ob;
        }

    }      

轉載于:https://www.cnblogs.com/Kendy/p/10271662.html