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= ...
随机推荐
- Nginx使用GeoIP模块来限制地区访问
举例比如限制泰国地区的IP访问: 前提条件,安装了http geoip 或stream geoip模块的Nginx Plus或者开源nginx Maxmind的GeoLite Legacy数据库 1. ...
- Nginx实现高可用(了解)
使用nginx实现反向代理和负载均衡时,nginx就是整个网站的入口了,所以需要保证nginx的高可用 主要资料包:链接:https://pan.baidu.com/s/1z_-xEM3uUICtZi ...
- 使用maven的profile构建不同环境配置
基本概念说明(resources.filter和profile): 1.profiles定义了各个环境的变量id 2.filters中定义了变量配置文件的地址,其中地址中的环境变量就是上面profil ...
- 代理损失函数(surrogate loss function)
Surrogate loss function,中文可以译为代理损失函数.当原本的loss function不便计算的时候,我们就会考虑使用surrogate loss function. 在二元分类 ...
- Flume介绍与安装
搭建环境 部署节点操作系统为CentOS,防火墙和SElinux禁用,创建了一个shiyanlou用户并在系统根目录下创建/app目录,用于存放 Hadoop等组件运行包.因为该目录用于安装hadoo ...
- mybatis动态拼接条件的技巧 where 1=1 或者where标签
/** * 根据输入的学生信息进行条件检索 * 1. 当只输入用户名时, 使用用户名进行模糊检索: * 2. 当只输入邮箱时, 使用性别进行完全匹配 * 3. 当用户名 ...
- thymeleaf+layui加载页面渲染时TemplateProcessingException: Could not parse as expression
Caused by: org.attoparser.ParseException: Could not parse as expression: " {type: 'numbers'}, { ...
- Quartz Version=3.0.4.0,Culture=neutral,PublickeyToken=f6b8c98a402cc8a4或它的一个依赖项。找到的程序集清单定义与程序集引用不匹配
报这种错误,就是比对Quartz的版本 ,右击引用的dll,属性查看版本. 一个项目中要一样 或者接口和调用接口的要一样 . 思路:解决这种问题的思路就是比对版本号.有可能是其它的dll,但是思路 ...
- String的优化 Stringbuffer和Stringbuilder
string 上次说到string是最好衍生出来的一种字符类型,实现原理是由char[].我们知道数组一旦创建时不可更改的,所以每一次进行字符串的拼接都是在new一个新的字符串进行添加,这样的话对内存 ...
- [AI] 深度数据 - Data
Data Engineering Data Pipeline Outline [DE] How to learn Big Data[了解大数据] [DE] Pipeline for Data Eng ...