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相互转换的更多相关文章

  1. C#.net开发 List与DataTable相互转换 【转】

    http://blog.csdn.net/shuizhaoshui/article/details/51425527 在.NET开发中,操作关系型数据库提取数据经常用到DataTable.ASP.NE ...

  2. XML IList<T> TO DataSet TO DataTable 相互转换

    //遍历XML 获得 DataSet //XmlTextReader static void Main(string[] args) { string xmlData = @"D:\stud ...

  3. Asp.net常用开发方法之DataTable/DataReader转Json格式代码

    public static string JsonParse(OleDbDataReader dataReader) //DataRead转json { StringBuilder jsonStrin ...

  4. List泛型与DataTable相互转换

    public static class ExtensionMethods{/// <summary>/// 将List转换成DataTable/// </summary>/// ...

  5. 【转载】ArcEngine ITable 与System.DataTable相互转换

    /// <summary> /// 打开dbf表 /// </summary> /// <param name="pathName"></ ...

  6. 封装一个List集合和datatable相互转换的工具类(可对指定列进行重命名并且指定输出列)

    /// <summary> /// List转换为DataTable对象 /// </summary> public class ListTranTableModel { // ...

  7. json与DataTable相互转换

    首先我们看看 Newtonsoft.Json.JsonConvert 是怎么完成的: DataTable table = new DataTable(); table.Columns.Add(&quo ...

  8. XML与DataTable相互转换

    1.DataTable转XML #region DataTableToXml /// <summary> /// 将DataTable对象转换成XML字符串 /// </summar ...

  9. 【Winfrom-DataTable填充ListView】ListView与DataTable相互转换 .net

    1.DataTable转成ListView: 先遍历DataTable的列,把DataTable列名添加到listView列头. 然后外循环添加行,内循环添加列 跟这篇文章是一样的 http://ww ...

随机推荐

  1. SRS之SrsHls::on_video详解

    1. SrsHls::on_video /* * mux the video packets to ts. * @param shared_video, directly ptr, copy it i ...

  2. cvxpy给的ADMM_example报错

    x = Variable((3, 1), name="x") ValueError: Cannot broadcast dimensions  (3, 1) (3, ) 解决方案: ...

  3. 【软件工程】Beta冲刺(2/5)

    链接部分 队名:女生都队 组长博客: 博客链接 作业博客:博客链接 小组内容 恩泽(组长) 过去两天完成了哪些任务 描述 新增修改用户信息.任务完成反馈等功能API 服务器后端部署,API接口的bet ...

  4. [log4j]Error:The method getLogger(String) in the type Logger is not applicable for the arguments

    原因:本该导入import org.apache.log4j.Logger; 结果成了import java.util.logging.Logger; 如果硬把private static Logge ...

  5. linux服务之redis

    redis wget http://download.redis.io/releases/redis-4.0.6.tar.gzcd redis-4.0.6makecd src/./redis-serv ...

  6. String类的常用方法以及知识点总结

    一,String的简介: 查阅API中的String类的描述,发现String 类代表字符串.Java 程序中的所有字符串字面值(如 "abc" )都作为此类的实例实现. 一旦这个 ...

  7. WMPageController设置menuView的左右视图

    效果图如下: 绿色的是自定义的emenuView的rightView哟!!! 代码实现如下: // // CategoryVC.m // JSHui // // Created by Apple on ...

  8. linux硬件驱动

    今天被问到了一个新问题:linux需不需要安装驱动,就像windows装完系统之后需要安装最新驱动一样? 说实话以前真没想过,都是装完系统update一下就直接用了. 谷歌了一下,发现其实也是需要安装 ...

  9. centos7修复grub2

    GRUB  :“the Grand Unified Bootloader ”引导加载程序 1.主要配置文件 #/boot/grub2/grub.cfg #rm -rf /boot/grub2/grub ...

  10. PHP学习(9)——错误和异常处理

    1.Exception类 这个类是PHP为异常处理提供的内置类.构造函数的两个参数分别是错误消息和错误代码. 除了构造函数之外,该类还提供了如下的内置方法: · getCode() 返回传递给构造函数 ...