首页 > 其他 > 详细

[工具类]DataTable与泛型集合List互转

时间:2015-12-04 12:34:06      阅读:313      评论:0      收藏:0      [点我收藏+]

写在前面

工作中经常遇到datatable与list,对于datatable而言操作起来不太方便。所以有的时候还是非常希望通过泛型集合来进行操作的。所以这里就封装了一个扩展类。也方便使用。

方法中主要使用了反射的方式动态的为属性赋值以及取值。

 public static class Extension
    {
        /// <summary>
        /// 将datatable转换为泛型集合
        /// </summary>
        /// <typeparam name="TEntity"></typeparam>
        /// <param name="inputDataTable"></param>
        /// <returns></returns>
        public static List<TEntity> ToList<TEntity>(this DataTable inputDataTable) where TEntity : class,new()
        {
            if (inputDataTable == null)
            {
                throw new ArgumentNullException("input datatable is null");
            }
            Type type = typeof(TEntity);
            PropertyInfo[] propertyInfos = type.GetProperties();
            List<TEntity> lstEntitys = new List<TEntity>();
            foreach (DataRow row in inputDataTable.Rows)
            {
                object obj = Activator.CreateInstance(type);
                foreach (PropertyInfo pro in propertyInfos)
                {
                    pro.SetValue(obj, row[pro.Name]);
                }
                TEntity tEntity = obj as TEntity;
                lstEntitys.Add(tEntity);
            }
            return lstEntitys;
        }
        /// <summary>
        /// 将list转换为datatable
        /// </summary>
        /// <typeparam name="TEntity"></typeparam>
        /// <param name="inputList"></param>
        /// <returns></returns>
        public static DataTable ToDataTable<TEntity>(this List<TEntity> inputList) where TEntity : class,new()
        {
            if (inputList == null)
            {
                throw new ArgumentNullException("inputList");
            }
            DataTable dt = null;
            Type type = typeof(TEntity);
            if (inputList.Count == 0)
            {
                dt = new DataTable(type.Name);
                return dt;
            }
            PropertyInfo[] propertyInfos = type.GetProperties();
            foreach (var item in propertyInfos)
            {
                dt.Columns.Add(new DataColumn() { ColumnName = item.Name, DataType = item.PropertyType });
            }
            foreach (var item in inputList)
            {
                DataRow row = dt.NewRow();
                foreach (var pro in propertyInfos)
                {
                    row[pro.Name] = pro.GetValue(item);
                }
                dt.Rows.Add(row);
            }
            return dt;
        }
    }

总结

有些时候能偷懒就偷懒了,把常用的工具类自己封装下,下次使用的时候拿来用就可以了。

[工具类]DataTable与泛型集合List互转

原文:http://www.cnblogs.com/wolf-sun/p/5018901.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!