.net: 泛型List<T> 轉換成 DataTable類型
2024-09-04 16:50:44
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;
}
最新文章
- Java多线程11:ReentrantLock的使用和Condition
- Element is not currently visible and so may not be interacted with错误
- .Net中的Debug模式和Release模式
- Controller方法的返回值
- PV UV
- Android 的自定义Spinner组件实现方式
- oracle——用户
- GCD教程(三):Dispatch Sources
- 将百度坐标转换的javascript api官方示例改写成传统的回调函数形式
- qt的信号与槽函数
- 使用C# (.NET Core) 实现组合设计模式 (Composite Pattern)
- webpack 4.x之搭建前端开发环境
- pycharm import pygame 出现报错:No module named &#39;pygame&#39;
- (七)dubbo服务集群实现负载均衡
- 101. Symmetric对称 Tree
- mac版 android studio问题解决
- 跟我一起学习ASP.NET 4.5 MVC4.0(六)
- 分布式服务框架dubbo原理解析
- 漫谈JS 的继承方式
- Java中基于HotSpot虚拟机的垃圾收集器
热门文章
- linux下mariadb的下载与卸载
- Edge 自动给数字加下划线的问题
- Haar-like feature和Haar wavelet
- 关于spring”通配符的匹配很全面, 但无法找到元素 &#39;context:component-scan&#39; 的声明“的错误
- Displaying Speed and Direction Symbology from U and V vectors (转)
- 2014-4-2解决无法访问github和google的问题
- 课后练习Javascript
- 团队内的沟通方式:网络 OR 当面
- Eclipse下的Hadoop应用开发准备
- 上课总结-数据结构c++