.net core C# DataTable 和List之间相互转换的方法
一、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); |
.net core 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 ...
- C# DataTable 和List之间相互转换的方法(转载)
来源:https://www.cnblogs.com/shiyh/p/7478241.html 一.List<T>/IEnumerable转换到DataTable/DataView 方法一 ...
- 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程序中, ...
- IRandomAccessStream, IBuffer, Stream, byte[] 之间相互转换
/* * 用于实现 IRandomAccessStream, IBuffer, Stream, byte[] 之间相互转换的帮助类 */ using System;using System.IO;us ...
随机推荐
- “AI虚拟数字人+线下大屏互动”升级智能人机交互服务!
如今AIGC 强势爆发. ChatGPT 语言大模型横空出世,使得数字人的"大脑"水平得到了极大提升,AI技术赋能下的虚拟数字人拥有了更加精准的语言表达.思考逻辑.帮助各个行业实现 ...
- mysql 必知必会整理—全球化与本地化[十六]
前言 简单介绍一下字符集. 数据库表被用来存储和检索数据.不同的语言和字符集需要以不同的方式存储和检索. 因此,MySQL需要适应不同的字符集(不同的字母和字符),适应不同的排序和检索数据的方法. 字 ...
- Flask搭建APP统一管理平台
主页效果: 1.从数据库中获取所有APP的信息,每个卡片上展示APP名称.bundle id.版本构建历史记录,系统类型等构建信息 2.支持查询筛选,模糊查询 3.点击历史记录跳转APP历史记录详情页 ...
- 极致体验!基于阿里云 Serverless 快速部署 Function
简介: 云计算的不断发展,涌现出很多改变传统 IT 架构和运维方式的新技术,而以虚拟机.容器.微服务为代表的技术更是在各个层面不断提升云服务的技术能力,它们将应用和环境中很多通用能力变成了一种服务.但 ...
- 使用 rocketmq-spring-boot-starter 来配置、发送和消费 RocketMQ 消息
简介: 本文将 rocktmq-spring-boot 的设计实现做一个简单的介绍,读者可以通过本文了解将 RocketMQ Client 端集成为 spring-boot-starter 框架的开发 ...
- dotnet 记 TaskCompletionSource 的 SetException 可能将异常记录到 UnobservedTaskException 的问题
本文将记录 dotnet 的一个已知问题,且是设计如此的问题.假定有一个 TaskCompletionSource 对象,此对象的 Task 没有被任何地方引用等待.在 TaskCompletionS ...
- dotnet 6 HttpClientHandler 和 SocketsHttpHandler 有什么差别
本文来告诉大家在 dotnet 6 的 HttpClientHandler 和 SocketsHttpHandler 两个类型有什么不同 在创建 HttpClient 时,可以在 HttpClient ...
- Git基础使用指南-命令详解
Software is like sex: it's better when it's free. -- Linus Torvalds 前情须知 -O- 工作流程 首先要明确的是Git的工作流程,你使 ...
- 阿里云边缘容器云帮助AI推理应用快速落地
近日,阿里云技术专家徐若晨在全球分布式云大会上,分享了<边缘容器云助力AI推理高效落地>的主题演讲,分享了阿里云边缘容器云如何助力开发者实现更快速的AI推理应用的迭代和部署.此外,他还分享 ...
- Multisim仿真验证之二极管的特性参数
二极管的特性 正向 R1 10% 20% 30% 50% 70% 90% Vd/mV 299 543 583 608 627 658 Id/mA 0.01 0.1 0.6 1.4 2.8 7.2 rd ...