C#DataTable转List<T>互转
using System;
using System.Collections.Generic;
using System.Data;
using System.Reflection; namespace BT.Preservation.Models
{
public static class ExtendMethod
{
/// <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 ToDataTable<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;
}
}
}
C#DataTable转List<T>互转的更多相关文章
- DataTable 和Json 字符串互转
#region DataTable 转换为Json字符串实例方法 /// <summary> /// GetClassTypeJosn 的摘要说明 /// </summary> ...
- 二:C#对象、集合、DataTable与Json内容互转示例;
导航目录: Newtonsoft.Json 概述 一:Newtonsoft.Json 支持序列化与反序列化的.net 对象类型: 二:C#对象.集合.DataTable与Json内容互转示例: ...
- DataTable,List,Dictonary互转,筛选及相关写法
1.创建自定义DataTable /// 创建自定义DataTable(一) 根据列名字符串数组, /// </summary> /// <param name="sLi ...
- DataTable和List集合互转
/// <summary> /// 将集合转换成DataTable /// </summary> /// <param name="list"> ...
- C#中DataTable与泛型集合互转(支持泛型集合中对象包含枚举)
最近在做WCF,因为是内部接口,很多地方直接用的弱类型返回(DataSet),这其实是一种非常不好的方式,最近将项目做了修改,将所有接口返回值都修改成强类型,这样可以减少很多与客户端开发人员的沟通,结 ...
- c#常用的Datable转换为json,以及json转换为DataTable操作方法
#region DataTable 转换为Json字符串实例方法 /// <summary> /// GetClassTypeJosn 的摘要说明 /// </summary> ...
- [C#]Datatable和json互相转换操作
#region DataTable 转换为Json字符串实例方法 /// <summary> /// GetClassTypeJosn 的摘要说明 /// </summary> ...
- C#中把Datatable转换为Json的5个代码实例
一. /// <summary> /// Datatable转换为Json /// </summary> /// <param name="table" ...
- Datatable转成Json方式两则
1, Asp.net C# 使用Newtonsoft.Json 实现DataTable转Json格式数据 1.这里下载:http://www.newtonsoft.com/products/json/ ...
随机推荐
- js中跳转的方法
javascript中的location.href有很多种用法,主要如下. self.location.href="/url" 当前页面打开URL页面location.href=& ...
- Good Bye 2017 A B C
Good Bye 2017 A New Year and Counting Cards 题目链接: http://codeforces.com/contest/908/problem/A 思路: 如果 ...
- Calling the Web Service dynamically (.NET 动态访问Web Service)
针对.NET平台下的WebService访问,为达到不添加引用的情况下,动态调用外部服务. 主体方法: public class WebServiceHelper { //Calling the We ...
- Cisco 7200 路由 PPPOE 拨号详解
1.1配置虚拟拨号接口 R1(config)#vpdn enable #启用vpdn虚拟专用拨号网络 R1(config)#interface dialer 1 ...
- Spring Cloud第五篇 | 服务熔断Hystrix
本文是Spring Cloud专栏的第五篇文章,了解前四篇文章内容有助于更好的理解本文: Spring Cloud第一篇 | Spring Cloud前言及其常用组件介绍概览 Spring Clo ...
- 一台电脑如何管理多个ssh key
目录 一.生成ssh key 1.1 生成密钥(必须) 1.2 设置路径 (可选) 1.3 指定密语字符串(可选) 二.设置ssh key的代理 2.1. 首先查看代理 2.2. 添加私钥 三.添加公 ...
- [TimLinux] Python nonlocal和global的作用
1. 执行代码 以下实例都是通过执行以下代码,需要把以下执行代码放在后面实例代码的后面. a = outer_func()print("call a()") a() a() a() ...
- CoderForces999D-Equalize the Remainders
D. Equalize the Remainders time limit per test 3 seconds memory limit per test 256 megabytes input s ...
- CodeForces985C-Liebig's Barrels
描述 题解 二分加贪心.先确保前 ii 桶可以分配为相邻的 kk 个,并且保证 a[i∗k+j]−a[1]<=la[i∗k+j]−a[1]<=l,这样就能保证所有的差不大于 ll,如果不能 ...
- Asp.net Core 异常日志与API返回值处理
需求: 1.对异常进行捕获记录日志 并且修改返回值给前端 解释: ILogger4是自定义的一个日志,更改它就好 解决方案1: 使用中间件进行异常捕获并且修改其返回值 public class Err ...