using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks; namespace Com.AppCode.Extend
{
static public class TableConvert
{
#region DataTable 1
/// <summary>
/// 将datatable转换为泛型集合
/// </summary>
/// <typeparam name="TEntity"></typeparam>
/// <param name="inputDataTable"></param>
/// <returns></returns>
public static List<TEntity> ToList<TEntity>(this DataTable inputDataTable) where TEntity : class, new()
{
if (inputDataTable == null)
{
throw new ArgumentNullException("input datatable is null");
}
Type type = typeof(TEntity);
PropertyInfo[] propertyInfos = type.GetProperties();
List<TEntity> lstEntitys = new List<TEntity>();
foreach (DataRow row in inputDataTable.Rows)
{
object obj = Activator.CreateInstance(type);
foreach (PropertyInfo pro in propertyInfos)
{
foreach (DataColumn col in inputDataTable.Columns)
{
//如果直接查询的数据库,数据库是不区别大小写的,所以转换为小写忽略大小写的问题
if (col.ColumnName.ToLower().Equals(pro.Name.ToLower()))
{
//属性是否是可写的,如果是只读的属性跳过。
if (pro.CanWrite)
{
//判断类型,基本类型,如果是其他的类属性
if (pro.PropertyType == typeof(System.Int32))
{
pro.SetValue(obj, Convert.ToInt32(row[pro.Name.ToLower()]));
}
else if (pro.PropertyType == typeof(System.String))
{
pro.SetValue(obj, row[pro.Name.ToLower()].ToString());
}
else if (pro.PropertyType == typeof(System.Boolean))
{
pro.SetValue(obj, Convert.ToBoolean(row[pro.Name.ToLower()]));
}
else if (pro.PropertyType == typeof(System.DateTime))
{
pro.SetValue(obj, Convert.ToDateTime(row[pro.Name.ToLower()]));
}
else if (pro.PropertyType == typeof(System.Int64))
{
pro.SetValue(obj, Convert.ToInt64(row[pro.Name.ToLower()]));
}
else
{
pro.SetValue(obj, row[pro.Name.ToLower()]);
} }
}
}
}
TEntity tEntity = obj as TEntity;
lstEntitys.Add(tEntity);
}
return lstEntitys;
}
/// <summary>
/// 将list转换为datatable
/// </summary>
/// <typeparam name="TEntity"></typeparam>
/// <param name="inputList"></param>
/// <returns></returns>
public static DataTable ToDataTable<TEntity>(this List<TEntity> inputList) where TEntity : class, new()
{
if (inputList == null)
{
throw new ArgumentNullException("inputList");
}
DataTable dt = null;
Type type = typeof(TEntity);
if (inputList.Count == )
{
dt = new DataTable(type.Name);
return dt;
}
else { dt = new DataTable(); }
PropertyInfo[] propertyInfos = type.GetProperties();
foreach (var item in propertyInfos)
{
dt.Columns.Add(new DataColumn() { ColumnName = item.Name, DataType = item.PropertyType });
}
foreach (var item in inputList)
{
DataRow row = dt.NewRow();
foreach (var pro in propertyInfos)
{
row[pro.Name] = pro.GetValue(item);
}
dt.Rows.Add(row);
}
return dt;
}
#endregion #region DataTable 2 /// <summary>
/// DataTable转成List
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="dt"></param>
/// <returns></returns>
public static List<T> ToDataList<T>(this DataTable dt)
{
var list = new List<T>();
var plist = new List<PropertyInfo>(typeof(T).GetProperties());
foreach (DataRow item in dt.Rows)
{
T s = Activator.CreateInstance<T>();
for (int i = ; i < dt.Columns.Count; i++)
{
PropertyInfo info = plist.Find(p => p.Name == dt.Columns[i].ColumnName);
if (info != null)
{
try
{
if (!Convert.IsDBNull(item[i]))
{
object v = null;
if (info.PropertyType.ToString().Contains("System.Nullable"))
{
v = Convert.ChangeType(item[i], Nullable.GetUnderlyingType(info.PropertyType));
}
else
{
v = Convert.ChangeType(item[i], info.PropertyType);
}
info.SetValue(s, v, null);
}
}
catch (Exception ex)
{
throw new Exception("字段[" + info.Name + "]转换出错," + ex.Message);
}
}
}
list.Add(s);
}
return list;
} /// <summary>
/// DataTable转成Dto
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="dt"></param>
/// <returns></returns>
public static T ToDataDto<T>(this DataTable dt)
{
T s = Activator.CreateInstance<T>();
if (dt == null || dt.Rows.Count == )
{
return s;
}
var plist = new List<PropertyInfo>(typeof(T).GetProperties());
for (int i = ; i < dt.Columns.Count; i++)
{
PropertyInfo info = plist.Find(p => p.Name == dt.Columns[i].ColumnName);
if (info != null)
{
try
{
if (!Convert.IsDBNull(dt.Rows[][i]))
{
object v = null;
if (info.PropertyType.ToString().Contains("System.Nullable"))
{
v = Convert.ChangeType(dt.Rows[][i], Nullable.GetUnderlyingType(info.PropertyType));
}
else
{
v = Convert.ChangeType(dt.Rows[][i], info.PropertyType);
}
info.SetValue(s, v, null);
}
}
catch (Exception ex)
{
throw new Exception("字段[" + info.Name + "]转换出错," + ex.Message);
}
}
}
return s;
} /// <summary>
/// 将实体集合转换为DataTable
/// </summary>
/// <typeparam name="T">实体类型</typeparam>
/// <param name="entities">实体集合</param>
public static DataTable ToTable<T>(List<T> entities)
{
var result = CreateTable<T>();
FillData(result, entities);
return result;
} /// <summary>
/// 创建表
/// </summary>
private static DataTable CreateTable<T>()
{
var result = new DataTable();
var type = typeof(T);
foreach (var property in type.GetProperties(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance))
{
var propertyType = property.PropertyType;
if ((propertyType.IsGenericType) && (propertyType.GetGenericTypeDefinition() == typeof(Nullable<>)))
propertyType = propertyType.GetGenericArguments()[];
result.Columns.Add(property.Name, propertyType);
}
return result;
} /// <summary>
/// 填充数据
/// </summary>
private static void FillData<T>(DataTable dt, IEnumerable<T> entities)
{
foreach (var entity in entities)
{
dt.Rows.Add(CreateRow(dt, entity));
}
} /// <summary>
/// 创建行
/// </summary>
private static DataRow CreateRow<T>(DataTable dt, T entity)
{
DataRow row = dt.NewRow();
var type = typeof(T);
foreach (var property in type.GetProperties(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance))
{
row[property.Name] = property.GetValue(entity) ?? DBNull.Value;
}
return row;
} #endregion #region DataTable 3
/// <summary>
/// DataTable转换为List
/// </summary>
/// <typeparam name="T">实体对象</typeparam>
/// <param name="dt">datatable表</param>
/// <returns>返回list集合</returns> static public List<T> TableToList<T>(DataTable dt) where T : new()
{
//定义集合
List<T> list = new List<T>();
//获得此模型的类型
Type type = typeof(T);
//定义一个临时变量
string tempName = string.Empty;
//遍历Datatable中所有的数据行
foreach (DataRow dr in dt.Rows)
{
T t = new T();
//获得此模型的公共属性
PropertyInfo[] propertys = t.GetType().GetProperties();
//遍历该对象的所有属性
foreach (PropertyInfo pi in propertys)
{
//将属性名称赋值给临时变量
tempName = pi.Name;
//检查DataTable是否包含此列(列名==对象的属性名)
if (dt.Columns.Contains(tempName))
{
//判断此属性是否有Setter
if (!pi.CanWrite) continue;//该属性不可写,直接跳出
//取值
object value = dr[tempName];
//如果非空,则赋给对象的属性
if (value != DBNull.Value)
{
//加一重if判断,如果属性值是int32类型的,就进行一次强制转换
if (pi.GetMethod.ReturnParameter.ParameterType.Name == "Int32")
{
value = Convert.ToInt32(value);
}
pi.SetValue(t, value, null);
} }
}
//对象添加到泛型集合中
list.Add(t);
}
return list;
}
#endregion
}
}

C# DataTable和List转换操作类的更多相关文章

  1. DataTable转List<Model>通用类【实体转换辅助类】

    /// <summary> /// DataTable转List<Model>通用类[实体转换辅助类] /// </summary> public class Mo ...

  2. C# 利用ffmpeg 对视频转换系类操作 (1) 基本分析

    最近公司做一个项目,开发一个视频站点.项目需求中有很多视频转换的需求,如:格式转换(flv,Mp4),视频水印,视频截图,视频合成,获取视频的基本信息(时间戳,视频大小等).经过网络的收集资料以及自己 ...

  3. Excel 操作类

    转载:http://www.cnblogs.com/fellowcheng/archive/2010/08/21/1805158.html ExcelHelper(Excel2007) Code hi ...

  4. 基于 Aspose.Cells与XML导入excel 数据----操作类封装

    前言 导入excel数据, 在每个项目中基本上都会遇到,第三方插件或者基于微软office,用的最多的就是npoi,aspose.cells和c#基于office这三种方式,其中各有各的优缺点,在这也 ...

  5. C# Excel操作类 ExcelHelper

    实现C#与Excel文件的交互操作,实现以下功能: 1.DataTable 导出到 Excel文件 2.Model数据实体导出到 Excel文件[List<Model>] 3.导出数据到模 ...

  6. Linq转换操作之OfType,Cast,AsEnumerable,ToLookup源码分析

    Linq转换操作之OfType,Cast,AsEnumerable,ToLookup源码分析 一:Tolookup 1. 从方法的注解上可以看到,ToLookup也是一个k,v的形式,那么问题来了,它 ...

  7. XML序列化 判断是否是手机 字符操作普通帮助类 验证数据帮助类 IO帮助类 c# Lambda操作类封装 C# -- 使用反射(Reflect)获取dll文件中的类型并调用方法 C# -- 文件的压缩与解压(GZipStream)

    XML序列化   #region 序列化 /// <summary> /// XML序列化 /// </summary> /// <param name="ob ...

  8. C#---数据库访问通用类、Access数据库操作类、mysql类 .[转]

    原文链接 //C# 数据库访问通用类 (ADO.NET)using System;using System.Collections.Generic;using System.Text;using Sy ...

  9. C#---数据库访问通用类、Access数据库操作类、mysql类 .

    //C# 数据库访问通用类 (ADO.NET)using System;using System.Collections.Generic;using System.Text;using System. ...

随机推荐

  1. oracle sql insert插入字符&

    最近遇到insert 语句插入&字符报弹出框,如下: sql: insert into test_ldl001 (ID, NAME) values (', '/test/test.do?act ...

  2. Messagebox自定义计时关闭

    Messagebox自定义计时关闭 新建Winform项目WindowsFormsAppTESTMessageBoxAutoClose 主窗体代码 using System;using System. ...

  3. Assertion failure in -[UISectionRowData refreshWithSection:tableView:tableViewRowData:]

    最近在项目中遇到了 Assertion failure in -[UISectionRowData refreshWithSection:tableView:tableViewRowData:] 这个 ...

  4. JDK&JRE

    JDK是提供给Java开发人员使用的,其中包含了java的开发工具,也包括了JRE.所以安装了JDK,就不用在单独安装JRE了. 其中的开发工具:编译工具(javac.exe) 打包工具(jar.ex ...

  5. request请求模拟导出文件

    ui界面: 实现代码: def export(self,host): '''导出课时券记录''' #测试接口 url='https://'+host+r'/ticket-record/export?t ...

  6. 获取src 内容

    获取(代码): ].src; // 测试无效 修改(代码): 1 $("#img").attr('src',path);

  7. 【已解决】HttpWebRequest的GetResponse或GetRequestStream偶尔超时 + 总结各种超时死掉的可能和相应的解决办法

    [问题] 用C#模拟网页登陆,其中去请求几个页面,会发起对应的http的请求request,其中keepAlive设置为true,提交请求后,然后会有对应的response: resp = (Http ...

  8. 通过Httpclient工具类,实现接口请求

    package luckyweb.seagull.util; import org.apache.http.NameValuePair; import org.apache.http.client.e ...

  9. golang web框架 beego 学习 (五) 配置文件

    app.conf: appname = gowebProject httpport = runmode = dev copyrequestbody = true [db] host= localhos ...

  10. 经典PID控制及应用体会总结

    经典PID控制及应用体会总结 PID控制原理 PID是一种线性控制器,它根据给定值rin(t)与实际输出值yout(t)构成控制方案: 重点关注相关算法是如何对偏差进行处理的: PID控制器各校正环节 ...