convert datatable to List<T>

 public class DataConvert
    {  
        public static List<T> ConvertDataTable<T>(DataTable dt)
        {
            List<T> data = new List<T>();
            foreach (DataRow row in dt.Rows)
            {
                T item = GetItem<T>(row);
                data.Add(item);
            }
            return data;
        }
        public static T GetItem<T>(DataRow dr)
        {
            Type temp = typeof(T);
            T obj = Activator.CreateInstance<T>();

            var properties = temp.GetProperties();

            for(int i=0;i<properties.Length;i++)
            {
                var prop = properties[i];
                var itemValue = dr.ItemArray[i];
                if(itemValue!=DBNull.Value)
                {
                    prop.SetValue(obj, itemValue, null);
                }                             
            }

            //foreach (DataColumn column in dr.Table.Columns)
            //{
            //    foreach (PropertyInfo pro in temp.GetProperties())
            //    {
            //        if (pro.Name == column.ColumnName)
            //            pro.SetValue(obj, dr[column.ColumnName], null);
            //        else
            //            continue;
            //    }
            //}
            return obj;
        }
    }

 

posted @ 2019-08-28 22:04  FredGrit  阅读(162)  评论(0编辑  收藏  举报