List<T> 转化为DataTable,使用Array.ForEach()

来源:互联网 发布:淘宝旧版本下载2016 编辑:程序博客网 时间:2024/04/29 00:17
        public static DataTable ToDataTable<T>(this IEnumerable<T> list)        {            if (list == null || list.Count() == 0)            {                return null;            }            List<PropertyInfo> pList = new List<PropertyInfo>();            Type type = typeof(T);            DataTable dt = new DataTable();            Array.ForEach<PropertyInfo>(type.GetProperties(),                p =>                {                    pList.Add(p);                     dt.Columns.Add(p.Name, p.PropertyType);                });            foreach (var item in list)            {                DataRow row = dt.NewRow();                pList.ForEach(p => row[p.Name] = p.GetValue(item, null));                dt.Rows.Add(row);            }            return dt;        }

上面的方法,会出现System.Nullable<>的错误,修改后,如下:

    public static class Utility    {        public static DataTable ToDataTable<T>(this List<T> list)        {            if (list == null || list.Count == 0)            {                return null;            }            //定义一个属性集合            List<PropertyInfo> properties = new List<PropertyInfo>();            Type type = typeof(T);            DataTable table = new DataTable();            Array.ForEach<PropertyInfo>(type.GetProperties(),                p =>                {                    properties.Add(p); //把属性加入到集合                    table.Columns.Add(p.Name, p.PropertyType);  //添加DataTable的列                });            foreach (var item in list)            {                //创建DataRow                DataRow row = table.NewRow();                //赋值                properties.ForEach(p => row[p.Name] = p.GetValue(item, null));                table.Rows.Add(row);            }            return table;        }    }