写在前面

工作中经常遇到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)
{
foreach (DataColumn col in inputDataTable.Columns)
{
//如果直接查询的数据库,数据库是不区别大小写的,所以转换为小写忽略大小写的问题
if (col.ColumnName.ToLower().Equals(pro.Name.ToLower()))
{
//属性是否是可写的,如果是只读的属性跳过。
if (pro.CanWrite)
{
//判断类型,基本类型,如果是其他的类属性
if (pro.PropertyType == typeof(System.Int32))
{
pro.SetValue(obj, Convert.ToInt32(row[pro.Name.ToLower()]));
}
else if (pro.PropertyType == typeof(System.String))
{
pro.SetValue(obj, row[pro.Name.ToLower()].ToString());
}
else if (pro.PropertyType == typeof(System.Boolean))
{
pro.SetValue(obj, Convert.ToBoolean(row[pro.Name.ToLower()]));
}
else if (pro.PropertyType == typeof(System.DateTime))
{
pro.SetValue(obj, Convert.ToDateTime(row[pro.Name.ToLower()]));
}
else if (pro.PropertyType == typeof(System.Int64))
{
pro.SetValue(obj, Convert.ToInt64(row[pro.Name.ToLower()]));
}
else
{
pro.SetValue(obj, row[pro.Name.ToLower()]);
} }
}
}
}
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 == )
{
dt = new DataTable(type.Name);
return dt;
}else{dt=new DataTable();}
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互转的更多相关文章

  1. C#中DataTable与泛型集合互转(支持泛型集合中对象包含枚举)

    最近在做WCF,因为是内部接口,很多地方直接用的弱类型返回(DataSet),这其实是一种非常不好的方式,最近将项目做了修改,将所有接口返回值都修改成强类型,这样可以减少很多与客户端开发人员的沟通,结 ...

  2. POI读取excel工具类 返回实体bean集合(xls,xlsx通用)

    本文举个简单的实例 读取上图的 excel文件到 List<User>集合 首先 导入POi 相关 jar包 在pom.xml 加入 <!-- poi --> <depe ...

  3. 使用jackson工具类把对象或集合转为JSON格式

    jackson使用方法: 1.加入jar包: jackson-annotations-2.2.2.jar jackson-core-2.2.2.jar jackson-databind-2.2.2.j ...

  4. List集合工具类之"将list集合按"指定长度"进行切分Lists.partition和ListUtils.partition"

    将list集合按"指定长度"进行切分,返回新的List<List<类型>>集合,如下的:  方法1:List<List<Integer>& ...

  5. 第29天学习打卡(迭代器、泛型 、Collection工具类、set集合的特点及应用、Map集合的特点及应用)

    迭代器 对过程的重复,称为迭代. 迭代器是遍历Collection集合的通用方式,可以在对集合遍历的同时进行添加.删除等操作. 迭代器的常用方法 next():返回迭代的下一个元素对象 hasNext ...

  6. 集合工具类CollectionUtils、ListUtils、SetUtils、MapUtils的使用

    主要用它的isEmpty(final Collection<?> coll)静态方法来判断一个给定的集合是否为null或者是否长度为0.最近才发现此工具类还可以取集合的交集.并集.甚至差集 ...

  7. 集合工具类CollectionUtils、ListUtils、SetUtils、MapUtils探究(转)

    之前一直以为集合工具类只有CollectionUtils,主要用它的isEmpty(final Collection<?> coll)静态方法来判断一个给定的集合是否为null或者是否长度 ...

  8. Java从入门到放弃18---Map集合/HashMap/LinkedHashMap/TreeMap/集合嵌套/Collections工具类常用方法

    Java从入门到放弃18—Map集合/HashMap/LinkedHashMap/TreeMap/集合嵌套/Collections工具类常用方法01 Map集合Map集合处理键值映射关系的数据为了方便 ...

  9. [Google Guava] 2.3-强大的集合工具类:java.util.Collections中未包含的集合工具

    原文链接 译文链接 译者:沈义扬,校对:丁一 尚未完成: Queues, Tables工具类 任何对JDK集合框架有经验的程序员都熟悉和喜欢java.util.Collections包含的工具方法.G ...

随机推荐

  1. 解决ubuntu sudo not found command的问题

    将/etc/sudoers 中Defaults env_reset改成Defaults !env_reset取消掉对PATH变量的重置, 然后在/etc/bash.bashrc中最后添加alias s ...

  2. pushd

    # MAN 手册原文:        pushd [-n] [+n] [-n]        pushd [-n] [dir]               Adds  a  directory to ...

  3. 【转载】chromium浏览器开发系列第一篇:如何获取最新chromium源码

    背景:     最近摊上一个事儿,领导非要让写一篇技术文章,思来想去,自己接触chrome浏览器时间也不短了,干脆就总结一下吧.于是乎,本文顺理成章.由于有些细节必需描述清楚,所以这次先讲如何拿到ch ...

  4. Linux shell basic2 cat find tr

    Cat stands for concatenate. Case 1. When the text files have more blank lines, we want to remove the ...

  5. Cassandra 分布式集群

    1 实施Cassandra集群,并验证集群功能正常,抓图实验过程 2 为什么说对于布隆过滤器有"确定某个元素是否在某个集合中的代价和总的元素数目无关"?误判率和元素数目有关吗?为什 ...

  6. 边工作边刷题:70天一遍leetcode: day 84-2

    要点:这题是combination的应用,从左向右想比从右向左容易. 因为有结果从小到大的要求,暗示用combintion而不是permutation 其实就是从小到大验证因子,每个因子和其对称因子立 ...

  7. Codeforces Round #258 D Count Good Substrings --计数

    题意:由a和b构成的字符串,如果压缩后变成回文串就是Good字符串.问一个字符串有几个长度为偶数和奇数的Good字串. 分析:可知,因为只有a,b两个字母,所以压缩后肯定为..ababab..这种形式 ...

  8. SpringBoot 快速入门

    本篇文章翻译来源为:http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/ 首先springboot ...

  9. 手机中点击链接或button按钮出现黄色边框的解决办法

    a,input,button{outline: none; -webkit-tap-highlight-color: rgba(255, 255, 255, 0); -webkit-focus-rin ...

  10. 基于PXC的MySQL高可用环境简单部署

    PXC简介 Percona XtraDB Cluster(简称PXC集群)提供了MySQL高可用的一种实现方法. 1.集群是有节点组成的,推荐配置至少3个节点,但是也可以运行在2个节点上. 2.每个节 ...