List<T>/IEnumerable转换到DataTable/DataView

方法一:

/// <summary>

/// Convert a List{T} to a DataTable.

/// </summary>

private DataTable ToDataTable<T>(List<T> items)

{

var tb = new DataTable(typeof (T).Name);

PropertyInfo[] props = typeof (T).GetProperties(BindingFlags.Public | BindingFlags.Instance);

foreach (PropertyInfo prop in props)

{

Type t = GetCoreType(prop.PropertyType);

tb.Columns.Add(prop.Name, t);

}

foreach (T item in items)

{

var values = new object[props.Length];

for (int i = 0; i < props.Length; i++)

{

values[i] = props[i].GetValue(item, null);

}

tb.Rows.Add(values);

}

return tb;

}

/// <summary>

/// Determine of specified type is nullable

/// </summary>

public static bool IsNullable(Type t)

{

return !t.IsValueType || (t.IsGenericType && t.GetGenericTypeDefinition() == typeof(Nullable<>));

}

/// <summary>

/// Return underlying type if type is Nullable otherwise return the type

/// </summary>

public static Type GetCoreType(Type t)

{

if (t != null && IsNullable(t))

{

if (!t.IsValueType)

{

return t;

}

else

{

return Nullable.GetUnderlyingType(t);

}

}

else

{

return t;

}

}

方法二:

public static DataTable ToDataTable<T>(IEnumerable<T> collection)

{

var props = typeof(T).GetProperties();

var dt = new DataTable();

dt.Columns.AddRange(props.Select(p => new DataColumn(p.Name, p.PropertyType)).ToArray());

if (collection.Count() > 0)

{

for (int i = 0; i < collection.Count(); i++)

{

ArrayList tempList = new ArrayList();

foreach (PropertyInfo pi in props)

{

object obj = pi.GetValue(collection.ElementAt(i), null);

tempList.Add(obj);

}

object[] array = tempList.ToArray();

dt.LoadDataRow(array, true);

}

}

return dt;

}

二、DataTable转换到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);

}

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 T CreateItem<T>(DataRow row)

{

T obj = default(T);

if (row != null)

{

obj = Activator.CreateInstance<T>();

foreach (DataColumn column in row.Table.Columns)

{

PropertyInfo prop = obj.GetType().GetProperty(column.ColumnName);

try

{

object value = row[column.ColumnName];

prop.SetValue(obj, value, null);

}

catch

{  //You can log something here

//throw;

}

}

}

return obj;

}

方法二:

using System;

using System.Collections.Generic;

using System.Text;

using System.Data;

using System.Reflection;

namespace NCL.Data

{

/// <summary>

/// 实体转换辅助类

/// </summary>

public class ModelConvertHelper<T> where   T : new()

{

public static IList<T> ConvertToModel(DataTable dt)

{

// 定义集合

IList<T> ts = new List<T>();

// 获得此模型的类型

Type type = typeof(T);

string tempName = "";

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)

pi.SetValue(t, value, null);

}

}

ts.Add(t);

}

return ts;

}

}

}

使用方式:

// 获得查询结果

DataTable dt = DbHelper.ExecuteDataTable(...);

// 把DataTable转换为IList<UserInfo>

IList<UserInfo> users = ModelConvertHelper<UserInfo>.ConvertToModel(dt);

转载于:https://www.cnblogs.com/lgx5/p/6890595.html

C# DataTable 和List之间相互转换的方法相关推荐

  1. list,numpy,tensor之间相互转换的方法

    list,numpy,tensor之间相互转换的方法: a=[[1,2],[3,4]]#list print(a) b=np.array(a)#list->numpy print(b) c=to ...

  2. c++ string 数组_PHP数组与字符串之间相互转换的方法

    php中可以将数组转换成字符串的形式,也可以将字符串通过某个特定的规律转化成数组.那具体如何做呢?今天这篇文章就来说一说php中数组与字符串之间相互转换的方法. PHP 数组转换成字符串的方法 php ...

  3. 内核程序中进程的pid,handle,eprocess之间相互转换的方法

    在内核程序开发中,我们常常需要取得某进程的pid或句柄,或者需要检索进程的eprocess结构,很多API函数需要的参数也不同,所以掌握pid<->handle<->eproc ...

  4. C# DataTable和List之间相互转换

    目录 前言 想法 两者的区别 个人想法 完整代码 方式一 方式二 类型转换 前言 最近在捣鼓DataTable,弄到了类型转换,既然弄了,那就整个记录.有不足之处,请多多指教.我看了一下目前的转换方式 ...

  5. 学习Python必须要会的,在字符串,列表,元组三者之间相互转换的方法

    1.字符串转换成列表 str='Lara1798' print(list(str))# 运行结果:['L', 'a', 'r', 'a', '1', '7', '9', '8'] 2.列表转换成字符串 ...

  6. C++ 数字与字符串之间相互转换(多种方法)

    使用系统提供的库函数 1.字符串传数字  (1).使用stoi() string s("12345"); long long a = stoi(s); cout << ...

  7. c语言xml序列化,C# XML和实体类之间相互转换(序列化和反序列化)

    我们需要在XML与实体类,DataTable,List之间进行转换,下面是XmlUtil类,该类来自网络并稍加修改. using System; using System.Collections.Ge ...

  8. 使用C++实现YUV格式图像与RGB格式图像之间相互转换

    使用C++实现YUV格式图像与RGB格式图像之间相互转换 一.RGB与YUV转换公式 1.RGB转YUV 1)RGB转换亮度与色差信号公试: 2)归一化为YUV的转化公试为: 2.YUV转RGB 二. ...

  9. .mat,.txt,.csv 数据转换为weka中的arff格式及matlab和Weka之间相互转换格式

    在RUSBoost和SMOTEBoost中提供了csv转换为arff格式的方法,详见CSVtoARFF.m http://www.mathworks.com/matlabcentral/fileexc ...

最新文章

  1. sql如何让计算出来的结果百分数显示_图解面试题:如何交换数据?
  2. HDU2029:Palindromes _easy version
  3. arthas 排查内存溢出_小学妹问我:如何利用可视化工具排查问题?
  4. Date和TimeZone的关系
  5. Elasticsearch索引备份与清理
  6. 工作流与Petri net的关系
  7. 使用 Source Generator 自动生成 WEB API
  8. 大型计算机变形,计算机变形病毒的主要特征和发展趋势
  9. 毛概社会实践报告3000字
  10. 得物回应中消协点名批评:感谢监督 涉及案例已处理完结
  11. iphone4 白苹果解决方法 刷机+越狱
  12. 注销 睡眠 休眠的区别
  13. 国内外 48 个最常用学术网站汇总,这可能是史上最全的!
  14. java applet插件_Atitit.java的浏览器插件技术 Applet japplet attilax总结
  15. [NLP] 秒懂词向量Word2vec的本质+word2vec资源总结
  16. 计算机辅助出版的英文缩写是,计算机辅助设计的英文缩写为
  17. 计算机屏幕怎么拆,aoc显示器怎么拆解?拿掉器的拆解方法!
  18. Excel函数大全-01最常用的十个函数
  19. Python脚本抓取大乐透开奖结果核对定投号码邮件通知
  20. 《微信朋友圈,这么玩才赚钱》读书笔记-刘焱飞

热门文章

  1. Hotel POJ - 3667(线段树 + 区间合并
  2. Netty(三) 什么是 TCP 拆、粘包?如何解决?
  3. 黄学长模拟day1 球的序列
  4. android学习笔记42——图形图像处理2——绘图
  5. [0716] Jsoi B Isbn
  6. Spring框架中IoC(控制反转)的原理
  7. 集成 Tomcat、 Servlet 的生命周期
  8. VMware客户端vSphere Web Client新建虚拟机
  9. PathCopyCopy一键复制文件路径
  10. Hadoop问题解决记录