DataTable转换为List 【拓展方法】

来源:互联网 发布:淘宝店铺设计公司 编辑:程序博客网 时间:2024/03/19 11:32
public static class ReflectionHelper    {        public static List<T> ToList<T>(this DataTable dt) where T : class        {            Type type = typeof(T);            List<T> list = new List<T>();            PropertyInfo[] infos = type.GetProperties();            foreach (DataRow item in dt.Rows)            {                object obj = Activator.CreateInstance(type);                for (int i = 0; i < infos.Length; i++)                {                    //判断当前属性是否可写以及数据源是否存在、是否为NULL。                    if (infos[i].CanWrite && dt.Columns.Contains(infos[i].Name) && item[infos[i].Name] != DBNull.Value)                        infos[i].SetValue(obj, Convert.ChangeType(item[infos[i].Name], infos[i].PropertyType), null);                }                list.Add(obj as T);            }            return list;        }    }

0 0
原创粉丝点击