C# 泛型DataTable转对象List
来源:互联网 发布:c语言中如何打开文件 编辑:程序博客网 时间:2024/05/22 12:47
/// <summary>
/// Table转List
/// </summary>
/// <param name="dt"></param>
/// <returns></returns>
public List<T> TableToList(DataTable dt)
{
var result = new List<T>();
var type = typeof(T);
foreach (DataRow row in dt.Rows)
{
PropertyInfo[] array = type.GetProperties(); //集合属性数组
var entity = Activator.CreateInstance<T>(); //新建对象实例
foreach (var p in array)
{
if (!dt.Columns.Contains(p.Name) || row[p.Name] == null || row[p.Name] == DBNull.Value)
{
continue;
}
if (p.PropertyType == typeof(DateTime) && Convert.ToDateTime(row[p.Name]) < Convert.ToDateTime("1753-01-01"))
{
continue;
}
try
{
//类型强转,将table字段类型转为集合字段类型
var obj = Convert.ChangeType(row[p.Name], p.PropertyType);
p.SetValue(entity, obj, null);
}
catch (Exception)
{
continue;
}
}
result.Add(entity);
}
return result;
}
/// Table转List
/// </summary>
/// <param name="dt"></param>
/// <returns></returns>
public List<T> TableToList(DataTable dt)
{
var result = new List<T>();
var type = typeof(T);
foreach (DataRow row in dt.Rows)
{
PropertyInfo[] array = type.GetProperties(); //集合属性数组
var entity = Activator.CreateInstance<T>(); //新建对象实例
foreach (var p in array)
{
if (!dt.Columns.Contains(p.Name) || row[p.Name] == null || row[p.Name] == DBNull.Value)
{
continue;
}
if (p.PropertyType == typeof(DateTime) && Convert.ToDateTime(row[p.Name]) < Convert.ToDateTime("1753-01-01"))
{
continue;
}
try
{
//类型强转,将table字段类型转为集合字段类型
var obj = Convert.ChangeType(row[p.Name], p.PropertyType);
p.SetValue(entity, obj, null);
}
catch (Exception)
{
continue;
}
}
result.Add(entity);
}
return result;
}
3 0
- C# 泛型DataTable转对象List
- C# List转DataTable(反射)
- c# DataTable转List 和 List转 DataTable
- 【C# 工具类】将DataTable转化为 List集合/对象
- dataTable转list C# asp.net
- JSON之Asp.net MVC C#对象转JSON,DataTable转JSON,List<T>转JSON,JSON转List<T>,JSON转C#对象
- JSON之Asp.net MVC C#对象转JSON,DataTable转JSON,List<T>转JSON,JSON转List<T>,JSON转C#对象
- C# DataTable 和List之间相互转换的方法[转]
- c# datatable 数据类型 转 泛型
- 泛型--datatable TO List
- List转DataTable
- List转DataTable(反射)
- DataTable转List
- DataTable转List
- list转DataTable
- List转DataTable(反射)
- datatable转LIST
- DataTable转List
- ajaxForm 与ajaxSubmit
- spring boot设置http https端口
- Jenkins自动化打包遇到的问题abc_list_focused_holo.9.png ERROR: Unable to open PNG file
- Sublime Text 3(全插件)配置和php5.5调试环境
- NYOJ 273 字母小游戏
- C# 泛型DataTable转对象List
- docker相关
- CMake find_package for OpenCV
- 移动端 1px 解决方案
- RF中变量转换
- Leetcode笔记整理—easy篇—Valid Parentheses
- android string.xml中使用占位符
- GitHub Android Libraries Top 100 简介
- android中xml tools属性详解