C#.net开发 List与DataTable相互转换
1、DataTable转List集合
/// <summary>
/// DataTable转化为List集合
/// </summary>
/// <typeparam name="T">实体对象</typeparam>
/// <param name="dt">datatable表</param>
/// <param name="isStoreDB">是否存入数据库datetime字段,date字段没事,取出不用判断</param>
/// <returns>返回list集合</returns>
public static List<T> TableToList<T>(DataTable dt, bool isStoreDB = true)
{
List<T> list = new List<T>();
Type type = typeof(T);
//List<string> listColums = new List<string>();
PropertyInfo[] pArray = type.GetProperties(); //集合属性数组
foreach (DataRow row in dt.Rows)
{
T entity = Activator.CreateInstance<T>(); //新建对象实例
foreach (PropertyInfo p in pArray)
{
if (!dt.Columns.Contains(p.Name) || row[p.Name] == null || row[p.Name] == DBNull.Value)
{
continue; //DataTable列中不存在集合属性或者字段内容为空则,跳出循环,进行下个循环
}
if (isStoreDB && p.PropertyType == typeof(DateTime) && Convert.ToDateTime(row[p.Name]) < Convert.ToDateTime("1753-01-01"))
{
continue;
}
try {
var obj = Convert.ChangeType(row[p.Name], p.PropertyType);//类型强转,将table字段类型转为集合字段类型
p.SetValue(entity, obj, null);
}
catch (Exception)
{
// throw;
}
//if (row[p.Name].GetType() == p.PropertyType)
//{
// p.SetValue(entity, row[p.Name], null); //如果不考虑类型异常,foreach下面只要这一句就行
//}
//object obj = null;
//if (ConvertType(row[p.Name], p.PropertyType,isStoreDB, out obj))
//{
// p.SetValue(entity, obj, null);
//}
}
list.Add(entity);
}
return list;
}
isStoreDB形参是在考虑List转化的DataTale数据要不要存储数据库,sqlserver数据中,时间类型date和datetime范围不同,date时间范围是在元年1月1日到9999年12月31日,datetime时间范围是在1753年1月1日到9999年12月31日,不在范围内的时间存储到数据库产生异常,因此加上时间限定,默认为存入数据库中数据。
2、List集合转DataTable
/// <summary>
/// List集合转DataTable
/// </summary>
/// <typeparam name="T">实体类型</typeparam>
/// <param name="list">传入集合</param>
/// <param name="isStoreDB">是否存入数据库DateTime字段,date时间范围没事,取出展示不用设置TRUE</param>
/// <returns>返回datatable结果</returns>
public static DataTable ListToTable<T>(List<T> list, bool isStoreDB = true)
{
Type tp = typeof(T);
PropertyInfo[] proInfos = tp.GetProperties();
DataTable dt = new DataTable();
foreach (var item in proInfos)
{
dt.Columns.Add(item.Name, item.PropertyType); //添加列明及对应类型
}
foreach (var item in list)
{
DataRow dr = dt.NewRow();
foreach (var proInfo in proInfos)
{
object obj = proInfo.GetValue(item);
if (obj == null)
{
continue;
}
//if (obj != null)
// {
if (isStoreDB && proInfo.PropertyType == typeof(DateTime) && Convert.ToDateTime(obj) < Convert.ToDateTime("1753-01-01"))
{
continue;
}
// dr[proInfo.Name] = proInfo.GetValue(item);
dr[proInfo.Name] = obj;
// }
}
dt.Rows.Add(dr);
}
return dt;
}
3、提取DataTable某一行转为指定对象
/// <summary>
/// table指定行转对象
/// </summary>
/// <typeparam name="T">实体</typeparam>
/// <param name="dt">传入的表格</param>
/// <param name="rowindex">table行索引,默认为第一行</param>
/// <returns>返回实体对象</returns>
public static T TableToEntity<T>(DataTable dt, int rowindex = , bool isStoreDB = true)
{
Type type = typeof(T);
T entity = Activator.CreateInstance<T>(); //创建对象实例
if (dt == null)
{
return entity;
}
//if (dt != null)
//{
DataRow row = dt.Rows[rowindex]; //要查询的行索引
PropertyInfo[] pArray = type.GetProperties();
foreach (PropertyInfo p in pArray)
{
if (!dt.Columns.Contains(p.Name) || row[p.Name] == null || row[p.Name] == DBNull.Value)
{
continue;
} if (isStoreDB && p.PropertyType == typeof(DateTime) && Convert.ToDateTime(row[p.Name]) < Convert.ToDateTime("1753-01-02"))
{
continue;
}
try
{
var obj = Convert.ChangeType(row[p.Name], p.PropertyType);//类型强转,将table字段类型转为对象字段类型
p.SetValue(entity, obj, null);
}
catch (Exception)
{
// throw;
}
// p.SetValue(entity, row[p.Name], null);
}
// }
return entity;
}
C#.net开发 List与DataTable相互转换的更多相关文章
- C#.net开发 List与DataTable相互转换 【转】
http://blog.csdn.net/shuizhaoshui/article/details/51425527 在.NET开发中,操作关系型数据库提取数据经常用到DataTable.ASP.NE ...
- XML IList<T> TO DataSet TO DataTable 相互转换
//遍历XML 获得 DataSet //XmlTextReader static void Main(string[] args) { string xmlData = @"D:\stud ...
- Asp.net常用开发方法之DataTable/DataReader转Json格式代码
public static string JsonParse(OleDbDataReader dataReader) //DataRead转json { StringBuilder jsonStrin ...
- List泛型与DataTable相互转换
public static class ExtensionMethods{/// <summary>/// 将List转换成DataTable/// </summary>/// ...
- 【转载】ArcEngine ITable 与System.DataTable相互转换
/// <summary> /// 打开dbf表 /// </summary> /// <param name="pathName"></ ...
- 封装一个List集合和datatable相互转换的工具类(可对指定列进行重命名并且指定输出列)
/// <summary> /// List转换为DataTable对象 /// </summary> public class ListTranTableModel { // ...
- json与DataTable相互转换
首先我们看看 Newtonsoft.Json.JsonConvert 是怎么完成的: DataTable table = new DataTable(); table.Columns.Add(&quo ...
- XML与DataTable相互转换
1.DataTable转XML #region DataTableToXml /// <summary> /// 将DataTable对象转换成XML字符串 /// </summar ...
- 【Winfrom-DataTable填充ListView】ListView与DataTable相互转换 .net
1.DataTable转成ListView: 先遍历DataTable的列,把DataTable列名添加到listView列头. 然后外循环添加行,内循环添加列 跟这篇文章是一样的 http://ww ...
随机推荐
- AngularJS复习小结
开发移动端App,首先得在头部 <meta name="viewport" content="width=device-width, initial-scale=1 ...
- cvxpy给的ADMM_example报错
x = Variable((3, 1), name="x") ValueError: Cannot broadcast dimensions (3, 1) (3, ) 解决方案: ...
- SilverFish
noHero123/silverfish https://github.com/noHero123/silverfish/blob/master/HrtBddy/instructions.txt Ho ...
- goland 可用注册码(license)
N757JE0KCT-eyJsaWNlbnNlSWQiOiJONzU3SkUwS0NUIiwibGljZW5zZWVOYW1lIjoid3UgYW5qdW4iLCJhc3NpZ25lZU5hbWUiO ...
- Android 关于 CountDownTimer onTick() 倒计时不准确问题源码分析
一.问题 CountDownTimer 使用比较简单,设置 5 秒的倒计时,间隔为 1 秒. final String TAG = "CountDownTimer"; * , ) ...
- Matlab获取一个文件夹下所有文件名
Matlab获取一个文件夹下所有文件名: fileFolder=fullfile('D:\MATLAB\bin\trc'); dirOutput=dir(fullfile(fileFolder,'*. ...
- Ubuntu14.04+安卓系统4.3+JDK6编译源码
本博客主要参照: https://www.jianshu.com/p/ecb9c132030f https://blog.csdn.net/gobitan/article/details/243674 ...
- composer install与composer update的区别
1.composer install install 命令从当前目录读取 composer.json 文件,处理了依赖关系,并把其安装到 vendor 目录下. php composer.phar i ...
- Springboot入门5-项目打包部署(转载)
前言 本文主要介绍SpringBoot的一些打包事项和项目部署以及在其中遇到一些问题的解决方案. SpringBoot打包 在SpringBoot打包这块,我们就用之前的一个web项目来进行打包.首先 ...
- 为什么单个TCP连接很难占满带宽
计算 TCP吞吐量的公式 TCP窗口大小(bits) / 延迟(秒) = 每秒吞吐量(bits) 比如说windows系统一般的窗口大小为64K, 中国到美国的网络延迟为150ms. 64KB = 6 ...