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的实现类的更多相关文章

  1. LINQ返回DataTable类型 list转dataset 转换为JSON对象

    using System.Web.Script.Serialization; using System.Collections.Generic; using System.Reflection; us ...

  2. C#之DataTable转List与List转Datatable

    闲来无事,只有写代码啦,以下为DataTable转List与List转DataTable的两个方法,主要技术点用到了反射原理: /// <summary> /// 模型转换类 /// &l ...

  3. C# DataTable转List And List转DataTable

    // DataTable转List: IList<HousesEntity> Ilist = TableAndList.ConvertTo<HousesEntity>(dt); ...

  4. “DataTable”是“System.Data.DataTable”和“Microsoft.Office.Interop.Excel.DataTable”之间的不明确的引用

    “DataTable”是“System.Data.DataTable”和“Microsoft.Office.Interop.Excel.DataTable”之间的不明确的引用 造成这个错误的原因是,在 ...

  5. 多个不同的表合并到一个datatable中,repeater在绑定datatable

    using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.UI ...

  6. 将两个列不同的DataTable合并成一个新的DataTable

    /// <summary>         /// 将两个列不同(结构不同)的DataTable合并成一个新的DataTable         /// </summary> ...

  7. EasyUI - Datatable转Json and Json转Datatable

    using System; using System.Data; using System.Linq; using System.Collections; using System.Collectio ...

  8. DataSet转换为泛型集合和DataRow 转成 模型类

    public static class TransformToList { /// <summary> /// DataSet转换为泛型集合 /// </summary> // ...

  9. C#给DataTable添加序号、C#给DataTable添加合计、小计

    /// <summary>        /// 给DataTable添加序号        /// </summary>        /// <param name= ...

随机推荐

  1. Python作业本——前言

    大四毕业了,9月才开始研究生生涯,导师也没有严格要求我暑假留校做项目,也没提具体的学习要求.这两三个月比较闲,所以就打算学学Python.学习过程中肯定会有些心得体会,以及一些小练习.学习编程不同于传 ...

  2. Spring Cloud同步场景分布式事务怎样做?试试Seata

    一.概述 在微服务架构下,虽然我们会尽量避免分布式事务,但是只要业务复杂的情况下这是一个绕不开的问题,如何保证业务数据一致性呢?本文主要介绍同步场景下使用Seata的AT模式来解决一致性问题. Sea ...

  3. SQL查询出距当前时间最近的一条或多条记录。

    select * from bas_dredge,(SELECT C_ENTERPRISEID,MAX(D_UTIME) D_LTIME FROM BAS_DREDGE GROUP BY C_ENTE ...

  4. java基本数据类型与引用类型

    基本数据类型: byte:Java中最小的数据类型,在内存中占8位(bit),即1个字节,取值范围-128~127,默认值0 short:短整型,在内存中占16位,即2个字节,取值范围-32768~3 ...

  5. 从零开始入门 K8s| 阿里技术专家详解 K8s 核心概念

    作者| 阿里巴巴资深技术专家.CNCF 9个 TCO 之一 李响 一.什么是 Kubernetes Kubernetes,从官方网站上可以看到,它是一个工业级的容器编排平台.Kubernetes 这个 ...

  6. Golang 入门系列(十五)如何理解go的并发?

    前面已经讲过很多Golang系列知识,感兴趣的可以看看以前的文章,https://www.cnblogs.com/zhangweizhong/category/1275863.html, 接下来要说的 ...

  7. 自定义 behavior - 完美仿 QQ 浏览器首页,美团商家详情页

    使用CoordinatorLayout打造各种炫酷的效果 自定义Behavior -- 仿知乎,FloatActionButton隐藏与展示 NestedScrolling 机制深入解析 一步步带你读 ...

  8. netty源码解解析(4.0)-22 ByteBuf的I/O

        ByteBuf的I/O主要解决的问题有两个: 管理readerIndex和writerIndex.这个在在AbstractByteBuf中解决. 从内存中读写数据.ByteBuf的不同实现主要 ...

  9. 深入理解Three.js中正交摄像机OrthographicCamera

    前言 在深入理解Three.js中透视投影照相机PerspectiveCamera那篇文章中讲解了透视投影摄像机的工作原理以及对应一些参数的解答,那篇文章中也说了会单独讲解Three.js中另一种常用 ...

  10. new的执行过程