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. TCP/IP协议族-----21、文件传送:FTP和TFTP

    watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvaGVrZXdhbmd6aQ==/font/5a6L5L2T/fontsize/400/fill/I0JBQk ...

  2. Linux-查看进程的完整路径

    通过ps及top命令查看进程信息时,只能查到相对路径,查不到的进程的详细信息,如绝对路径等.这时,我们需要通过以下的方法来查看进程的详细信息:Linux在启动一个进程时,系统会在/proc下创建一个以 ...

  3. QT Unexpected CDB exit 问题的解决办法

    行QT进行debug时,提示 Unexpected CDB exit ,The CBD process terminated.. QtCreator 默认是没有调试器的,因此需要用户额外安装. win ...

  4. jsp版本的环境变量集合

    System.out.println("Protocol: " + request.getProtocol());System.out.println("Scheme: ...

  5. document.documentElement.scrollTop

    要获取当前页面的滚动条纵坐标位置, 用:      document.documentElement.scrollTop; 而不是:      document.body.scrollTop; doc ...

  6. Android中Context的总结及其用法

    在android中我们经常遇到这样的情况,在创建一个对象的时候往往需要传递一个this参数,比如:语句 MyView mView = new MyView(this),要求传递一个this参数,这个t ...

  7. Hadoop文件解压缩

    Class org.apache.hadoop.io.compress .CompressionCodecFactory A factory that will find the correct co ...

  8. DEDECMS 添加栏目图片

    当我们一个栏目列表都用缩略图来表示产,而不仅仅只是文字,如果没有这项功能会非常麻烦,网上有很多这方面的资料,但是都试过了有很多问题,自己研究一下,测试基本通过.需要新加字段 typeimg 后台执行S ...

  9. freeswitch与外部网关链接

    我建了一个 Freeswitch 内核研究 交流群, 45211986, 欢迎加入, 另外,提供基于SIP的通信服务器及客户端解决方案, 承接 sip/ims 视频客户端开发,支持接入sip软交换,i ...

  10. Objective-C中的类型转换

    转自:http://blog.csdn.net/lonelyroamer/article/details/7711920 类型转换 表2-3列出了简单数据类型.示例和格式符. 表2-3 简单数据类型. ...