【代码】DataTable转换成List<T>集合

来源:互联网 发布:pdf编辑mac版 编辑:程序博客网 时间:2024/05/15 22:05

粗略的版本。

    public class DataTableToList<T> where T : class, new()    {        /// <summary>        /// DataTable转换成Model对象。        /// 2014年3月4日15:49:00        /// </summary>        /// <param name="table"></param>        /// <returns></returns>        public static List<T> GetModelList(DataTable table)        {            List<T> list = new List<T>();            foreach (DataRow item in table.Rows)            {                // 根据泛型创建实例                T t = Activator.CreateInstance<T>();                // 获得此模型的公共属性                PropertyInfo[] propertyInfos = t.GetType().GetProperties();                foreach (var propertyInfo in propertyInfos)                {                    string tempName = propertyInfo.Name;                    if (table.Columns.Contains(tempName))                    {                        if (!propertyInfo.CanWrite) continue;                        object value = item[tempName];                        if (value != DBNull.Value)                            propertyInfo.SetValue(t, value, null);                    }                }                list.Add(t);            }            return list;        }    }

调用。

                DataTable table = dbHelper.Query(sqlstr).Tables[0];                List<InvInventoryLog> list = DataTableToList<InvInventoryLog>.GetModelList(table);


0 0
原创粉丝点击