C#匿名转换 数据表转换

调用方式:
using System.Collections.Generic;
List<Model> list = Common.Uitil.TableToEntity<Model>(ds.Tables[0]);
return list[0];  
方法:
using System.Reflection;
using System.Data;
/// <summary>
        ///     
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="dt"></param>
        /// <returns></returns>
        public static List<T> TableToEntity<T>( DataTable dt) where T : class,new()
        {
            Type type = typeof (T);
            List<T> list = new List<T>();
            foreach (DataRow row in dt.Rows)
            {
                PropertyInfo[] pArray = type.GetProperties();
                T entity = new T();
                foreach (PropertyInfo p in pArray)
                {
                    try
                    {
                        if (row[p.Name] is Int64)
                        {
                            p.SetValue(entity, Convert.ToInt32(row[p.Name]), null );
                            continue;
                        }
                        p.SetValue(entity, row[p.Name], null);
                    }
                    catch (Exception e) { //continue;
                    }
                }
                list.Add(entity);
            }
           
            return list;
        }

  

posted @ 2020-08-05 17:46  sovf  阅读(168)  评论(0编辑  收藏  举报