DataTable与List<T>相互转换
2018-06-22 07:28:17来源:未知 阅读 ()
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace Common
{
public class ModelHelper
{
public static List<T> TableToEntity<T>(DataTable dt) where T : new()
{
List<T> lists = new List<T>();
if (dt.Rows.Count > 0)
{
foreach (DataRow row in dt.Rows)
{
lists.Add(SetVal(new T(), row));
}
}
return lists;
}
public static T SetVal<T>(T entity, DataRow row) where T : new()
{
Type type = typeof(T);
PropertyInfo[] pi = type.GetProperties();
foreach (PropertyInfo item in pi)
{
if (row[item.Name] != null && row[item.Name] != DBNull.Value)
{
if (item.PropertyType.IsGenericType && item.PropertyType.GetGenericTypeDefinition().Equals(typeof(Nullable<>)))
{
Type conversionType = item.PropertyType;
NullableConverter nullableConverter = new NullableConverter(conversionType);
conversionType = nullableConverter.UnderlyingType;
item.SetValue(entity, Convert.ChangeType(row[item.Name], conversionType), null);
}
else
{
item.SetValue(entity, Convert.ChangeType(row[item.Name], item.PropertyType), null);
}
}
}
return entity;
}
public static DataTable EntityToDataTable<T>(List<T> list) where T : new()
{
if (list == null || list.Count == 0)
{
return null;
}
DataTable dataTable = new DataTable(typeof(T).Name);
foreach (PropertyInfo propertyInfo in typeof(T).GetProperties())
{
if (propertyInfo.PropertyType.IsGenericType && propertyInfo.PropertyType.GetGenericTypeDefinition().Equals(typeof(Nullable<>)))
{
Type conversionType = propertyInfo.PropertyType;
NullableConverter nullableConverter = new NullableConverter(conversionType);
conversionType = nullableConverter.UnderlyingType;
dataTable.Columns.Add(new DataColumn(propertyInfo.Name, conversionType));
}
else
{
dataTable.Columns.Add(new DataColumn(propertyInfo.Name, propertyInfo.PropertyType));
}
}
foreach (T model in list)
{
DataRow dataRow = dataTable.NewRow();
foreach (PropertyInfo propertyInfo in typeof(T).GetProperties())
{
object value = propertyInfo.GetValue(model, null);
if (value != null)
{
dataRow[propertyInfo.Name] = propertyInfo.GetValue(model, null);
}
else
{
dataRow[propertyInfo.Name] = DBNull.Value;
}
}
dataTable.Rows.Add(dataRow);
}
return dataTable;
}
}
}
标签:
版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有
上一篇:ADO.NET
- DataSet与DataTable的区别示例介绍 2020-03-04
- asp.net实现导出DataTable数据到Word或者Excel的方法 2020-02-28
- .NET下通过HttpListener实现简单的Http服务 2020-02-27
- 详解ASP.NET控件之RadioButtonList 2019-11-17
- listview里的button事件添加方法 2019-10-08
IDC资讯: 主机资讯 注册资讯 托管资讯 vps资讯 网站建设
网站运营: 建站经验 策划盈利 搜索优化 网站推广 免费资源
网络编程: Asp.Net编程 Asp编程 Php编程 Xml编程 Access Mssql Mysql 其它
服务器技术: Web服务器 Ftp服务器 Mail服务器 Dns服务器 安全防护
软件技巧: 其它软件 Word Excel Powerpoint Ghost Vista QQ空间 QQ FlashGet 迅雷
网页制作: FrontPages Dreamweaver Javascript css photoshop fireworks Flash
