C# DataTable 和List之间相互转换的方法(转载)
来源:https://www.cnblogs.com/shiyh/p/7478241.html
一、List<T>/IEnumerable转换到DataTable/DataView
方法一:
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
|
/// <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; }} |
方法二:
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
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
方法一:
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
|
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; } |
方法二:
把查询结果以DataTable返回很方便,但是在检索数据时又很麻烦,没有模型类型检索方便。
所以很多人都是按照以下方式做的:
|
1
2
3
4
|
// 获得查询结果 DataTable dt = DbHelper.ExecuteDataTable(...); // 把DataTable转换为IList<UserInfo> IList<UserInfo> users = ConvertToUserInfo(dt); |
问题:如果此系统有几十上百个模型,那不是每个模型中都要写个把DataTable转换为此模型的方法吗?
解决:能不能写个通用类,可以把DataTable转换为任何模型,呵呵,这就需要利用反射和泛型了
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
|
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; } } } |
使用方式:
|
1
2
3
4
|
// 获得查询结果 DataTable dt = DbHelper.ExecuteDataTable(...); // 把DataTable转换为IList<UserInfo> IList<UserInfo> users = ModelConvertHelper<UserInfo>.ConvertToModel(dt); |
C# DataTable 和List之间相互转换的方法(转载)的更多相关文章
- C# DataTable 和List之间相互转换的方法
介绍:List/IEnumerable转换到DataTable/DataView,以及DataTable转换到List 正文: 一.List<T>/IEnumerable转换到DataTa ...
- 转 C# DataTable 和List之间相互转换的方法
一.List/IEnumerable转换到DataTable/DataView 方法一: /// <summary> /// Convert a List{T} to a DataTabl ...
- win32内核程序中进程的pid,handle,eprocess之间相互转换的方法
很有用,收下以后方便查询. 原贴地址:http://bbs.pediy.com/showthread.php?t=119193 在win32内核程序开发中,我们常常需要取得某进程的pid或句柄,或者需 ...
- 关于数组和List之间相互转换的方法
1.List转换成为数组:返回数组的运行时类型.如果列表能放入指定的数组.否则,将根据指定数组.如果指定的数组的元素比列表的多),那么会将存储列表元素的数组. 返回:包含列表元素的list.add(& ...
- DOS和UNIX文本文件之间相互转换的方法
在Unix/Linux下可以使用file命令查看文件类型,如下: file dosfile.txt 使用dos2unix 一般Linux发行版中都带有这个小工具,只能把DOS转换为UNIX文件,命令如 ...
- json对象与javaBean,String字符创之间相互转换的方法
原创:转载请注明出处 package com.allcam.system.utils; import com.fasterxml.jackson.databind.ObjectMapper; publ ...
- protobuf与json相互转换的方法
google的protobuf对象转json,不能直接使用FastJson之类的工具进行转换,原因是protobuf生成对象的get方法,返回的类型有byte[],而只有String类型可以作为jso ...
- 路由其实也可以很简单-------Asp.net WebAPI学习笔记(一) ASP.NET WebApi技术从入门到实战演练 C#面向服务WebService从入门到精通 DataTable与List<T>相互转换
路由其实也可以很简单-------Asp.net WebAPI学习笔记(一) MVC也好,WebAPI也好,据我所知,有部分人是因为复杂的路由,而不想去学的.曾经见过一位程序猿,在他MVC程序中, ...
- python datetime和unix时间戳之间相互转换
python datetime和unix时间戳之间相互转换 1.代码: import time import datetime # ...
随机推荐
- nodejs命令行执行时带参数
nodejs命令行执行时带参数 转 https://www.jianshu.com/p/474e6d76f867 今天项目里突然想在初始化时跑一些数据,于是想起以前在python时可以在命令行里带 ...
- Java 文件句柄泄露问题解决小记(转)
转:Java 文件句柄泄露问题解决小记 维护 WebIDE 免不了要管理很多的文件, 自从我们线上系统增加了资源回收功能,便一直受一个问题困扰:后台线程解绑目录时偶尔报错,看症状因为是某些文件被占用了 ...
- 转 linux 添加PHP环境变量,/etc/profile 不生效,每次都要 source /etc/profile
http://shanhuxueyuan.com/news/detail/46.html 执行php -v 提示未找到命令,这是因为没有将php路径添加到环境变量 方法一:直接运行命令export P ...
- EasyDSS高性能RTMP、HLS(m3u8)、HTTP-FLV、RTSP流媒体服务器与EasyDSS流媒体解决方案的不同
背景分析 众所周知,立足于视频软件的开发,我们的产品很多.经常有客户问到我们产品的差别以及某个产品在某个系统架构中的具体定位,因此我想通过一系列的博客说明一下,不同产品之间的区别,以及在具体架构中自身 ...
- 一步一步FLASK(一)
简介: 本文是记录本人建立一个flask项目的完整过程. 涉及FLASK的诸多实用技术. 一:基本FLASK pycharm建立FLASK项目即可运行. 代码如下: from flask import ...
- axios get,post请求时带headers
axios post请求时带headers: axios.post("http://xxx.com/xxx/xxx/xxx?", { 'queslistid': this.kemu ...
- 【并行计算-CUDA开发】OpenACC与OpenHMPP
在西雅图超级计算大会(SC11)上发布了新的基于指令的加速器并行编程标准,既OpenACC.这个开发标准的目的是让更多的编程人员可以用到GPU计算,同时计算结果可以跨加速器使用,甚至能用在多核CPU上 ...
- 【常用技巧】标准模板库(STL)
[常用技巧]标准模板库(STL) 在前几个章节中我们已经使用了诸如队列.堆.堆栈.vector 等标准模板库中的模板,切身感受到了它给我们带来的极大便利.在本节中,我们还要介绍两种标准模板——stri ...
- 【idea】全局搜索、替换只显示100条的问题
没有修改之前 修改之后 如果用的是idea默认的快捷键,按Ctrl+Shift+A,然后输入Registry 如果是eclipse的快捷键
- phpredis封装
<pre><?php/** * This is a Redis exntend class */ class RedisClient{ private static $instanc ...