DataTableHelper.cs 将DataTable转换为List,将List转换为DataTable的实现类
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks; namespace Xmh.DBUnit
{
/// <summary>
/// 将DataTable转换为List,将List转换为DataTable的实现类
/// </summary>
public static class DataTableHelper
{
public static DataTable ConvertTo<T>(IList<T> list)
{
DataTable table = CreateTable<T>();
Type entityType = typeof(T);
PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(entityType);
foreach (T item in list)
{
DataRow row = table.NewRow();
foreach (PropertyDescriptor prop in properties)
row[prop.Name] = prop.GetValue(item);
table.Rows.Add(row);
}
return table;
} public static IList<T> ConvertTo<T>(IList<DataRow> rows)
{
IList<T> list = null;
if (rows != null)
{
list = new List<T>();
foreach (DataRow row in rows)
{
T item = CreateItem<T>(row);
list.Add(item);
}
}
return list;
} public static IList<T> ConvertTo<T>(DataTable table)
{
if (table == null)
return null; List<DataRow> rows = new List<DataRow>();
foreach (DataRow row in table.Rows)
rows.Add(row); return ConvertTo<T>(rows);
} //Convert DataRow into T Object
public static T CreateItem<T>(DataRow row)
{
string columnName;
T obj = default(T);
if (row != null)
{
obj = Activator.CreateInstance<T>();
foreach (DataColumn column in row.Table.Columns)
{
columnName = column.ColumnName;
//Get property with same columnName
PropertyInfo prop = obj.GetType().GetProperty(columnName); try
{
Type type = prop.PropertyType;
//判断type类型是否为泛型,因为nullable是泛型类,
if (type.IsGenericType && type.GetGenericTypeDefinition().Equals(typeof(Nullable<>)))//判断convertsionType是否为nullable泛型类 {
//如果type为nullable类,声明一个NullableConverter类,该类提供从Nullable类到基础基元类型的转换
System.ComponentModel.NullableConverter nullableConverter = new System.ComponentModel.NullableConverter(type);
//将type转换为nullable对的基础基元类型
type = nullableConverter.UnderlyingType;
}
//Get value for the column
object value = (row[columnName].GetType() == typeof(DBNull))
? null : row[columnName];
//Set property value
if (prop.CanWrite) //判断其是否可写
prop.SetValue(obj, (value == null ? null : Convert.ChangeType(value, type)), null);
}
catch
{
throw;
//Catch whatever here
}
}
}
return obj;
} public static DataTable CreateTable<T>()
{
Type entityType = typeof(T);
DataTable table = new DataTable(entityType.Name);
PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(entityType); foreach (PropertyDescriptor prop in properties)
table.Columns.Add(prop.Name, prop.PropertyType); return table;
} public static List<T> ToList<T>(this DataTable dt) where T : class, new()
{
Type t = typeof(T);
PropertyInfo[] propertys = t.GetProperties();
List<T> lst = new List<T>();
string typeName = string.Empty;
foreach (DataRow dr in dt.Rows)
{
T entity = new T();
foreach (PropertyInfo pi in propertys)
{
typeName = pi.Name;
if (dt.Columns.Contains(typeName))
{
if (!pi.CanWrite) continue;
object value = dr[typeName];
if (value == DBNull.Value) continue;
if (pi.PropertyType == typeof(string))
{
pi.SetValue(entity, value.ToString(), null);
}
else if (pi.PropertyType == typeof(int) || pi.PropertyType == typeof(int?))
{
pi.SetValue(entity, int.Parse(value.ToString()), null);
}
else if (pi.PropertyType == typeof(DateTime?) || pi.PropertyType == typeof(DateTime))
{
pi.SetValue(entity, DateTime.Parse(value.ToString()), null);
}
else if (pi.PropertyType == typeof(float))
{
pi.SetValue(entity, float.Parse(value.ToString()), null);
}
else if (pi.PropertyType == typeof(double))
{
pi.SetValue(entity, double.Parse(value.ToString()), null);
}
else
{
pi.SetValue(entity, value, null);
}
}
}
lst.Add(entity);
}
return lst;
}
}
}
DataTableHelper.cs 将DataTable转换为List,将List转换为DataTable的实现类的更多相关文章
- LINQ返回DataTable类型 list转dataset 转换为JSON对象
using System.Web.Script.Serialization; using System.Collections.Generic; using System.Reflection; us ...
- C#之DataTable转List与List转Datatable
闲来无事,只有写代码啦,以下为DataTable转List与List转DataTable的两个方法,主要技术点用到了反射原理: /// <summary> /// 模型转换类 /// &l ...
- C# DataTable转List And List转DataTable
// DataTable转List: IList<HousesEntity> Ilist = TableAndList.ConvertTo<HousesEntity>(dt); ...
- “DataTable”是“System.Data.DataTable”和“Microsoft.Office.Interop.Excel.DataTable”之间的不明确的引用
“DataTable”是“System.Data.DataTable”和“Microsoft.Office.Interop.Excel.DataTable”之间的不明确的引用 造成这个错误的原因是,在 ...
- 多个不同的表合并到一个datatable中,repeater在绑定datatable
using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.UI ...
- 将两个列不同的DataTable合并成一个新的DataTable
/// <summary> /// 将两个列不同(结构不同)的DataTable合并成一个新的DataTable /// </summary> ...
- EasyUI - Datatable转Json and Json转Datatable
using System; using System.Data; using System.Linq; using System.Collections; using System.Collectio ...
- DataSet转换为泛型集合和DataRow 转成 模型类
public static class TransformToList { /// <summary> /// DataSet转换为泛型集合 /// </summary> // ...
- C#给DataTable添加序号、C#给DataTable添加合计、小计
/// <summary> /// 给DataTable添加序号 /// </summary> /// <param name= ...
随机推荐
- springboot统一ajax返回数据格式,并且jquery ajax success函数修改
服务端代码: package com.zhqn.sc.cfg; import org.springframework.core.MethodParameter; import org.springfr ...
- 使用Nginx实现反向代理过程(一台服务器部署两个网站)
正向代理指的是客户端的 反向代理指的是服务端的 需要实现的反向代理: 1.首先使用SwitchHosts配置不同域名,如下:(SwitchHosts软件在上一篇博客有链接) 2.在Linux上部署两台 ...
- pandas可视化:各种图的简单使用
一.Matplotlib中几种图的名字 折线图:plot 柱形图:bar 直方图:hist 箱线图:box 密度图:kde 面积图:area 散点图:scatter 散点图矩阵:scatter_mat ...
- 巨杉Tech | Hbase迁移至SequoiaDB 实战
背景 在传统银行 IT 架构中,联机交易与统计分析系统往往采用不同的技术与物理设备,通过定期执行的 ETL 将联机交易数据向分析系统中迁移.而作为数据服务资源池,同一份数据可能被不同类型的微服务共享访 ...
- RabbiMQ基础以及spring-boot-starter-amqp使用
RabbitMQ是一种基于amq协议的消息队列,本文主要记录一下rabbitmq的基础内容以及使用spring-boot-starter-amqp操作rabbitmq. 1,rabbitmq中的几 ...
- JVM性能监视
1,按照如下图步骤将-XX:PermSize及 -XX:MaxPermSize的值修改到足够小,故意造项目启动报错,我设置为32m.然后保存. 2.在IDE中启动tomcat的同时打开dos窗口,使用 ...
- crypto 的使用方法和说明
crypto 模块提供了加密功能,包含对 OpenSSL 的哈希.HMAC.加密.解密.签名.以及验证功能的一整套封装.我们这里讲crypto AES算法加密 一.使用步骤 1.引入Crypto 1. ...
- python pandas进行条件筛选时出现ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().”
在使用pandas进行条件筛选时,使用了如下的代码: fzd_index=data[(data['实际辐照度']<mi)or(data['实际辐照度']>ma)].index 原本以为,并 ...
- React + TypeScript 默认 Props 的处理
React 中的默认 Props 通过组件的 defaultProps 属性可为其 Props 指定默认值. 以下示例来自 React 官方文档 - Default Prop Values: clas ...
- Docker学习之docker常用命令
docker ps -a 表示所有容器 docker pull 获取image docker build 创建image docker run 运行container docker images 列出 ...