using System;
using System.Collections.Generic;
using System.Data;
using System.Reflection;
using System.ComponentModel;

public static class DataTableUtility
{
/// <summary>
/// DataTable To IList<T>
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="dt"></param>
/// <returns></returns>
public static IList<T> ToList<T>(this DataTable dt)
{
if (dt == null || dt.Rows.Count == 0) return null;
IList<T> list = new List<T>();
foreach (DataRow row in dt.Rows)
{
T obj = row.ToEntity<T>();
list.Add(obj);
}
return list;
}

/// <summary>
/// DataRow To T
/// </summary>
public static T ToEntity<T>(this DataRow row)
{
Type objType = typeof(T);
T obj = Activator.CreateInstance<T>();

foreach (DataColumn column in row.Table.Columns)
{
PropertyInfo property =
objType.GetProperty(column.ColumnName,
BindingFlags.Public | BindingFlags.Instance | BindingFlags.IgnoreCase);
if (property == null || !property.CanWrite)
{
continue;
}
object value = row[column.ColumnName];
if (value == DBNull.Value) value = null;

property.SetValue(obj, value, null);

}
return obj;
}

/// <summary>
/// List To DataTable
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="list"></param>
/// <returns></returns>
public static DataTable ToDataTable<T>(this List<T> list)
{
try
{
Type objType = typeof(T);
DataTable dataTable = new DataTable(objType.Name);
if (list != null ? list.Count > 0 : false)
{
PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(objType);
foreach (PropertyDescriptor property in properties)
{
Type propertyType = property.PropertyType;

//nullables must use underlying types
if (propertyType.IsGenericType && propertyType.GetGenericTypeDefinition() == typeof(Nullable<>))
propertyType = Nullable.GetUnderlyingType(propertyType);
//enums also need special treatment
if (propertyType.IsEnum)
propertyType = Enum.GetUnderlyingType(propertyType); //probably Int32

dataTable.Columns.Add(property.Name, propertyType);
}

foreach (T li in list)
{
DataRow row = dataTable.NewRow();
foreach (PropertyDescriptor property1 in properties)
{
row[property1.Name] = property1.GetValue(li) ?? DBNull.Value; //can't use null
}
dataTable.Rows.Add(row);

}
}
return dataTable;
}
catch
{
return null;
}
}
}

-----------------------------------------------------------------两个实体比较,如果值为空则给其赋值

/// <summary>
/// 将新实体中的正则提取差异字段值付给原始数据
/// </summary>
/// <param name="newEntity"></param>
/// <returns></returns>
public RecordEntity CombindDiff(RecordEntity newEntity)
{
Type patternType = this.GetType();
Type newType = newEntity.GetType();
//获取这个实体的所有属性(字段,属性等 例如 Name,sex等实体中字段)
PropertyInfo[] patternPInfos = patternType.GetProperties();
foreach (PropertyInfo patternPInfo in patternPInfos)
{
//得到字段的属性列表
object[] customInfos = patternPInfo.GetCustomAttributes(typeof(PatternAttributes), true);
if (customInfos == null
|| customInfos.Length == 0)
continue;
//获取自定义属性头(实体)
PatternAttributes patternAtrributes = customInfos.GetValue(0) as PatternAttributes;
//容器和非正则提取字段都不进行比较
if (patternAtrributes.IsContainerPattern
|| !patternAtrributes.IsPattern)
{
continue;
}
//获取对比实体属性值
object newVal = null;
//RecordEntity newEntity
//Type newType = newEntity.GetType();
//通过属性名得到实体
PropertyInfo newPatternPInfo = newType.GetProperty(patternPInfo.Name);

if (newPatternPInfo != null)
newVal = newPatternPInfo.GetValue(newEntity, null);

if (patternAtrributes.IsInt32Pattern
|| patternAtrributes.IsDateTimePattern)
{
patternPInfo.SetValue(this, newVal, null);
}
else
{
//当前提取结果是空时
if (newVal == null
|| newVal.ToString() == "")
continue;

patternPInfo.SetValue(this, newVal, null);
}
}
return this;
}

DataTable To Entity的更多相关文章

  1. Expression构建DataTable to Entity 映射委托

    namespace Echofool.Utility.Common { using System; using System.Collections.Generic; using System.Dat ...

  2. Newtonsoft.Json高级用法,json序列号,model反序列化,支持序列化和反序列化DataTable,DataSet,Entity Framework和Entity,字符串

    原文地址:https://www.cnblogs.com/yanweidie/p/4605212.html 手机端应用讲究速度快,体验好.刚好手头上的一个项目服务端接口有性能问题,需要进行优化.在接口 ...

  3. Expression构建DataTable to Entity 映射委托 sqlserver 数据库里面金额类型为什么不建议用float,实例告诉你为什么不能。 sql server 多行数据合并成一列 C# 字符串大写转小写,小写转大写,数字保留,其他除外 从0开始用U盘制作启动盘装Windows10系统(联想R720笔记本)并永久激活方法 纯CSS打造淘宝导航菜单栏 C# Winform

    Expression构建DataTable to Entity 映射委托   1 namespace Echofool.Utility.Common { 2 using System; 3 using ...

  4. 数据库查询 - DataTable转Entity类型数据

    当使用Sql语句查询数据库,返回DataSet数据集. DataSet转化为数据列表,可以通过映射方式直接返回Entity数据列表 新建一个特性类,用于数据库列表列名称映射 LinqToDB提供了一个 ...

  5. DataTable转Entity(Emit版)

    public static List<T> ToList<T>(DataTable dt)        {            List<T> list = n ...

  6. List转换为DataTable List<Entity>

    /// <summary> /// 将List转换成DataTable /// </summary> /// <typeparam name="T"& ...

  7. DataTable转换为Entity(反射&&泛型)

    public static IEnumerable<T> Parse<T>(IEnumerable<DataRow> rows) where T : class, ...

  8. 自用的基于Emit的C#下DataTable转实体类方法

    之前一直在做WebForm的开发,数据绑定时直接DataTable绑定Gridview很方便,但是最近开始往MVC转,数据列表的传递和页面展示基本上是以List为主,像下面这样,遍历实体类的各个字段去 ...

  9. Newtonsoft.Json高级用法DataContractJsonSerializer,JavaScriptSerializer 和 Json.NET即Newtonsoft.Json datatable,dataset,modle,序列化

    原文地址:https://www.cnblogs.com/yanweidie/p/4605212.html Newtonsoft.Json介绍 在做开发的时候,很多数据交换都是以json格式传输的.而 ...

随机推荐

  1. Nginx-负载均衡实践(一、对PHP-FPM进行分摊)

    应用的服务器分为前端和后端 前端服务器: 负责对静态文件(比如JS.CSS.图片)等的响应, 以及把PHP请求分发到后端服务器 后端服务器: 处理前端服务器分发而来的PHP请求 前端服务器: 192. ...

  2. [机器学习实战] 决策树ID3算法

    1. 决策树特点: 1)优点:计算复杂度不高,输出结果易于理解,对中间值的缺失不敏感,可以处理不相关特征数据. 2)缺点:可能会产生过度匹配问题. 3)适用数据类型:数值型和标称型. 2. 一般流程: ...

  3. C# 调用bat文件

    引入名称空间: using System.Diagnostics; Process proc = null; try { string targetDir = string.Format(@" ...

  4. MDK5.00中*** error 65: access violation at 0xFFFFFFFC : no 'write' permission的一种解决方法

    http://blog.csdn.net/coderfun/article/details/9417289 这是在调试过程中的修改方法,所以在每次运行的时候,都要设置. 先进入调试模式(crtl+F5 ...

  5. jQuery remove 内存 释放

    解决方案(伪代码):(http://www.cnblogs.com/see7di/archive/2011/09/08/2239653.html)jQuery( “*”, obj).add([obj] ...

  6. TLS线程局部存储

    0x01 TLS (Thread Local Storage) 为线程单独提供的私有空间 0x02 gcc中的隐式TLS使用方法 隐式TLS __thread int number; 显式TLS pt ...

  7. python学习之time模块

    time.time() 将时间作为浮点数返回. 在Windows和大多数Unix系统上,时代是1970年1月1日00:00:00(UTC),并且闰秒不计入从时代开始的秒数. >>> ...

  8. AxureRP_for_chorme的安装和使用方法

    1.下载AxureRP_for_chorme_version.crx 2.打开Chrome,右上角菜单图标->更多->扩展程序 3.将crx文件拖入,安装 4.选中AxureRP的“已启用 ...

  9. [转]C/C++中volatile关键字详解

    http://www.cnblogs.com/yc_sunniwell/archive/2010/07/14/1777432.html

  10. SessionListener失败,退出

    配置如下: web.xml: <listener> <listener-class>cn.edu.hbcf.common.listener.SessionListener< ...