C#中泛型举例List<T>与DataTable相互转换
作者:springsnow 时间:2021-07-06 18:54:08
一、 DataTable转换到List<T>
/// <summary>
/// TableToList
/// </summary>
public class TableListConverter<T> where T : class, new()
{
public static IList<T> TableToList(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;
if (dt.Columns.Contains(tempName))// 检查DataTable是否包含此列
{
if (!pi.CanWrite) continue;// 判断此属性是否有Setter
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 = TableListConverter<UserInfo>.TableToList(dt);
二、 List<T>转换到DataTable
/// <summary>
/// ListToTable
/// </summary>
public class TableListConverter
{
public static DataTable ListToTable<T>(IList<T> list) where T : class, new()
{
if (list == null) return null;
Type type = typeof(T);
DataTable dt = new DataTable();
PropertyInfo[] properties = Array.FindAll(type.GetProperties(), p => p.CanRead);//判断此属性是否有Getter
Array.ForEach(properties, prop => { dt.Columns.Add(prop.Name, prop.PropertyType); });//添加到列
foreach (T t in list)
{
DataRow row = dt.NewRow();
Array.ForEach(properties, prop =>
{
row[prop.Name] = prop.GetValue(t, null);
});//添加到行
dt.Rows.Add(row);
}
return dt;
}
}
应用:
//IList<UserInfo> users
DataTable dt =TableListConverter.ListToTable(users)
来源:https://www.cnblogs.com/springsnow/p/9428673.html
标签:C#,泛型,List,DataTable,相互,转换
0
投稿
猜你喜欢
c#中的浮点型转整形的舍取 四舍五入和银行家舍入实现代码
2023-01-10 02:04:41
dotnet如何将文件删除到回收站
2023-04-23 13:52:09
Java基础:流Stream详解
2023-11-29 06:11:14
Java四种常用线程池的详细介绍
2021-09-29 17:45:46
基于Java+SpringBoot+Vue前后端分离实现仓库管理系统
2023-11-01 04:21:22
在winform下实现左右布局多窗口界面的方法
2023-02-23 11:31:51
SpringMVC拦截器创建配置及执行顺序
2023-06-06 20:41:16
Android软键盘弹出时的界面控制方法
2022-10-26 03:37:43
Java List的sort()方法改写compare()实现升序,降序,倒序的案例
2021-12-30 06:22:58
java的arraylist排序示例(arraylist用法)
2023-01-15 06:55:37
Java的Struts框架中登陆功能的实现和表单处理器的使用
2022-05-20 23:44:45
.NET C#利用ZXing生成、识别二维码/条形码
2022-03-25 12:20:45
详解SpringMVC的url-pattern配置及原理剖析
2023-08-11 12:00:27
SpringBoot实现拦截器、过滤器、监听器过程解析
2023-07-01 02:34:52
java中计算字符串长度的方法及u4E00与u9FBB的认识
2022-07-15 18:28:20
Android连接服务器端的Socket的实例代码
2023-03-11 06:06:47
Android仿QQ微信实时监测网络状态
2022-10-10 06:48:52
Java switch使用原理及实例解析
2023-10-11 20:44:20
java 图片验证码的实现代码
2023-11-09 13:33:52
springboot热部署知识点总结
2021-08-23 12:05:43