C# 將DataTable 轉成list 泛型

 /// <summary>  
        /// DataTable 轉換爲List 集合  
        /// </summary>  
        /// <typeparam name="TResult">類型</typeparam>  
        /// <param name="dt">DataTable</param>  
        /// <returns></returns>  
        public static List<T> ToList<T>(this DataTable dt) where T : class, new()
        {
            //建立一個屬性的列表  
            List<PropertyInfo> prlist = new List<PropertyInfo>();
            //獲取TResult的類型實例  反射的入口  
            Type t = typeof(T);
            //得到TResult 的全部的Public 屬性 並找出TResult屬性和DataTable的列名稱相同的屬性(PropertyInfo) 並加入到屬性列表   
            Array.ForEach<PropertyInfo>(t.GetProperties(), p => { if (dt.Columns.IndexOf(p.Name) != -1) prlist.Add(p); });
            //建立返回的集合  
            List<T> oblist = new List<T>();this

            foreach (DataRow row in dt.Rows)
            {
                //建立TResult的實例  
                T ob = new T();
                //找到對應的數據  並賦值  
                prlist.ForEach(p => { if (row[p.Name] != DBNull.Value) p.SetValue(ob, row[p.Name], null); });
                //放入到返回的集合中.  
                oblist.Add(ob);
            }
            return oblist;
        }  class

調用:foreach

相關文章
相關標籤/搜索