public static DataTable ListToDataTable<T>(List<T> entitys)
{ //检查实体集合不能为空
if (entitys == null || entitys.Count < )
{
return new DataTable();
} //取出第一个实体的所有Propertie
Type entityType = entitys[].GetType();
PropertyInfo[] entityProperties = entityType.GetProperties(); //生成DataTable的structure
//生产代码中,应将生成的DataTable结构Cache起来,此处略
DataTable dt = new DataTable("dt");
for (int i = ; i < entityProperties.Length; i++)
{
//dt.Columns.Add(entityProperties[i].Name, entityProperties[i].PropertyType);
dt.Columns.Add(entityProperties[i].Name);
} //将所有entity添加到DataTable中
foreach (object entity in entitys)
{
//检查所有的的实体都为同一类型
if (entity.GetType() != entityType)
{
throw new Exception("要转换的集合元素类型不一致");
}
object[] entityValues = new object[entityProperties.Length];
for (int i = ; i < entityProperties.Length; i++)
{
entityValues[i] = entityProperties[i].GetValue(entity, null); }
dt.Rows.Add(entityValues);
}
return dt;
}

最新文章

  1. Java多线程11:ReentrantLock的使用和Condition
  2. Element is not currently visible and so may not be interacted with错误
  3. .Net中的Debug模式和Release模式
  4. Controller方法的返回值
  5. PV UV
  6. Android 的自定义Spinner组件实现方式
  7. oracle——用户
  8. GCD教程(三):Dispatch Sources
  9. 将百度坐标转换的javascript api官方示例改写成传统的回调函数形式
  10. qt的信号与槽函数
  11. 使用C# (.NET Core) 实现组合设计模式 (Composite Pattern)
  12. webpack 4.x之搭建前端开发环境
  13. pycharm import pygame 出现报错:No module named &#39;pygame&#39;
  14. (七)dubbo服务集群实现负载均衡
  15. 101. Symmetric对称 Tree
  16. mac版 android studio问题解决
  17. 跟我一起学习ASP.NET 4.5 MVC4.0(六)
  18. 分布式服务框架dubbo原理解析
  19. 漫谈JS 的继承方式
  20. Java中基于HotSpot虚拟机的垃圾收集器

热门文章

  1. linux下mariadb的下载与卸载
  2. Edge 自动给数字加下划线的问题
  3. Haar-like feature和Haar wavelet
  4. 关于spring”通配符的匹配很全面, 但无法找到元素 &#39;context:component-scan&#39; 的声明“的错误
  5. Displaying Speed and Direction Symbology from U and V vectors (转)
  6. 2014-4-2解决无法访问github和google的问题
  7. 课后练习Javascript
  8. 团队内的沟通方式:网络 OR 当面
  9. Eclipse下的Hadoop应用开发准备
  10. 上课总结-数据结构c++