asp.net算法——泛型转换DataTable

        /// <summary>
        /// 泛型转换DataTable
        /// </summary>
        /// <typeparam name=”T”></typeparam>
        /// <param name=”list”></param>
        /// <returns></returns>
        public static DataTable ListToDataTable<T>(List<T> list)
        {
            DataTable dt = new DataTable();

            foreach (PropertyInfo info in typeof(T).GetProperties())
            {
                dt.Columns.Add(new DataColumn(info.Name, info.PropertyType));
            }
            if (list!=null && list.Count>0)
            {
                foreach (T t in list)
                {
                    DataRow row = dt.NewRow();
                    foreach (PropertyInfo info in typeof(T).GetProperties())
                    {
                        row[info.Name] = info.GetValue(t, null);
                    }
                    dt.Rows.Add(row);
                }
            }
            return dt;
        }

 

点赞