其实早就该写的,哈哈,不过今天刚想起来注册,热热手,就写一下,哈哈。

  直接上内容吧:

  建立一个控制台应用程序,

             List<students> Studentlist =
new List<students>{
new students{ Name = "zhagnsan1", Chinese = , Math = , English = },
new students{ Name = "zhagnsan2", Chinese = , Math = , English = },
new students{ Name = "zhagnsan3", Chinese = , Math = , English = }
};
DataTable dt = ListToDatatableHelper.ToDataTable(Studentlist);
this.dataGridView1.DataSource = dt; List<students> list = DatatableToListHelper.ConvertToList(dt);   public class students
  {
public string Name { get; set; }
public double English { get; set; }
public double Chinese { get; set; }
public double Math { get; set; }
  }

  ListToDatatableHelper.cs中的内容为:

 using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks; namespace ListToDatatable
{
public class ListToDatatableHelper
{
/// <summary>
/// Convert a List{T} to a DataTable.
/// </summary>
public static DataTable ToDataTable<T>(List<T> items)
{
var tb = new DataTable(typeof(T).Name); PropertyInfo[] props = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance); foreach (PropertyInfo prop in props)
{
Type t = GetCoreType(prop.PropertyType);
tb.Columns.Add(prop.Name, t);
} foreach (T item in items)
{
var values = new object[props.Length]; for (int i = ; i < props.Length; i++)
{
values[i] = props[i].GetValue(item, null);
} tb.Rows.Add(values);
} return tb;
} /// <summary>
/// Determine of specified type is nullable
/// </summary>
public static bool IsNullable(Type t)
{
return !t.IsValueType || (t.IsGenericType && t.GetGenericTypeDefinition() == typeof(Nullable<>));
} /// <summary>
/// Return underlying type if type is Nullable otherwise return the type
/// </summary>
public static Type GetCoreType(Type t)
{
if (t != null && IsNullable(t))
{
if (!t.IsValueType)
{
return t;
}
else
{
return Nullable.GetUnderlyingType(t);
}
}
else
{
return t;
}
} //*************************************************
/// <summary>
/// List转Datatable
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="table"></param>
/// <returns></returns>
public static IList<T> ConvertTo<T>(DataTable table)
{
if (table == null)
{
return null;
} List<DataRow> rows = new List<DataRow>(); foreach (DataRow row in table.Rows)
{
rows.Add(row);
} return ConvertTo<T>(rows);
} public static IList<T> ConvertTo<T>(IList<DataRow> rows)
{
IList<T> list = null; if (rows != null)
{
list = new List<T>(); foreach (DataRow row in rows)
{
T item = CreateItem<T>(row);
list.Add(item);
}
} return list;
} public static T CreateItem<T>(DataRow row)
{
T obj = default(T);
if (row != null)
{
obj = Activator.CreateInstance<T>(); foreach (DataColumn column in row.Table.Columns)
{
PropertyInfo prop = obj.GetType().GetProperty(column.ColumnName);
try
{
object value = row[column.ColumnName];
prop.SetValue(obj, value, null);
}
catch
{ //You can log something here
//throw;
}
}
} return obj;
}
}
}

  DatatableToListHelper.cs中的内容为:

 using NPOI.SS.Formula.Functions;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using static ListToDatatable.Form1; namespace ListToDatatable
{
class DatatableToListHelper
{
/// <summary>
/// 利用反射和泛型
/// </summary>
/// <param name="dt"></param>
/// <returns></returns>
public static List<students> ConvertToList(DataTable dt)
{
// 定义集合
List<students> ts = new List<students>(); // 获得此模型的类型
Type type = typeof(students);
//定义一个临时变量
string tempName = string.Empty;
//遍历DataTable中所有的数据行
foreach (DataRow dr in dt.Rows)
{
students t = new students();
// 获得此模型的公共属性
PropertyInfo[] propertys = t.GetType().GetProperties();
//遍历该对象的所有属性
foreach (PropertyInfo pi in propertys)
{
tempName = pi.Name;//将属性名称赋值给临时变量
//检查DataTable是否包含此列(列名==对象的属性名)
if (dt.Columns.Contains(tempName))
{
// 判断此属性是否有Setter
if (!pi.CanWrite) continue;//该属性不可写,直接跳出
//取值
object value = dr[tempName];
//如果非空,则赋给对象的属性
if (value != DBNull.Value)
pi.SetValue(t, value, null);
}
}
//对象添加到泛型集合中
ts.Add(t);
}
return ts;
}
}
}

  OK,这是引用类型的list转datatable,完毕。

C#中Datatable和List互相转换的更多相关文章

  1. SQL Server中提前找到隐式转换提升性能的办法

        http://www.cnblogs.com/shanksgao/p/4254942.html 高兄这篇文章很好的谈论了由于数据隐式转换造成执行计划不准确,从而造成了死锁.那如果在事情出现之前 ...

  2. 怎么实现ZBrush 4R7中界面视窗的快速转换

    本篇教程介绍ZBrush® 4R7界面的基本操作之转换界面视窗, 教程属于入门教程可以帮助新手快速入门.因为ZBrush工 作界面不同于其他我们所熟知的3D软件,初次接触ZBrush的时候难免会有所困 ...

  3. C#中DataTable中的Compute方法使用收集

    原文: C#中DataTable中的Compute方法使用收集 Compute函数的参数就两个:Expression,和Filter. Expresstion是计算表达式,关于Expression的详 ...

  4. C#中DataTable排序、检索、合并等操作实例

    转载引用至:http://www.jb51.net/article/49222.htm     一.排序1.获取DataTable的默认视图2.对视图设置排序表达式3.用排序后的视图导出的新DataT ...

  5. Java中数据类型及其之间的转换

    Java中数据类型及其之间的转换 基本的数据类型 基本类型有以下四种:1)int长度数据类型有:byte(8bits).short(16bits).int(32bits).long(64bits).2 ...

  6. ArcGIS中的坐标系定义与转换 (转载)

    原文:ArcGIS中的坐标系定义与转换 (转载) 1.基准面概念:  GIS中的坐标系定义由基准面和地图投影两组参数确定,而基准面的定义则由特定椭球体及其对应的转换参数确定,因此欲正确定义GIS系统坐 ...

  7. ArcGIS中利用ArcMap将地理坐标系转换成投影坐标系(从WKID=4326到WKID=102100)

    原文:ArcGIS中利用ArcMap将地理坐标系转换成投影坐标系(从WKID=4326到WKID=102100) 对于非地理专业的开发人员,对与这些生涩的概念,我们不一定都要了解,但是我们要理解,凡是 ...

  8. C# 中DataTable转成模型List

    C# 中DataTable转成模型List 引入using System.Reflection; 命名空间 使用注意实体类的属性名必须和DataTable的列名一致 使用: DBList<Sto ...

  9. sqlserver和oracle中对全半角的转换

    oracle中对全半角的转换 to_single_byte(c)转换成半角 to_multi_byte(c)转换成全角 SELECT To_single_byte('881898?71') FROM ...

随机推荐

  1. SAP安装前添加虚拟网卡步骤

    添加虚拟网卡: 打开控制面版中的设备管理器 点击菜单栏上的[操作(A)] 选择[添加过时硬盘件] 选择[ 安装我手动从列表选择的硬件(高级)(M) ],点击[下一步] 选择[网络适配器],点击[下一步 ...

  2. 关于浏览器对静态HTML页面的缓存问题

    症状: 刚才为了测试TOMCAT的BASIC安全验证,修改了tomcat-users.xml和/WEB-INF/web.xml之后进行测试,<url-pattern>/*<url-p ...

  3. swift百度地图api

    swift使用百度地图api遇到的坑 之前在Android上用过百度地图,以为大概类似,也没仔细看文档,结果被自己坑了 注意事项,http://developer.baidu.com/map/inde ...

  4. WiFi(802.11)基础

    参考: 1. Wireshark数据包分析实战(第2版) 2. wifi技术从了解到熟悉1----概念.802.11协议简述及四种主要物理组件.wifi适配层.wap_supplicant和wap_c ...

  5. svn:ignore 的用处

    用svn管理代码,一直以来都受到一件不爽事情的困扰: 1)有些文件或文件夹不想在commit的时候看到,虽然他们是non-versioned,比如*.bak.*.class,*.scc(vss文件), ...

  6. 关于如何自定义handler

    1.在web.config 中的webserver 下添加 <handlers> <add verb="*" path="*.html" ty ...

  7. Ubuntu libpng png++安装

    http://blog.csdn.net/xiaozhun07/article/details/49865785 png使用过程问题小结: (1) libpng “png_set_longjmp_fn ...

  8. 基于struts2框架文件的上传与下载

    在开发一些社交网站时,需要有允许用户上传自己本地文件的功能,则需要文件的上传下载代码. 首先考虑的是文件的储存位置,这里不考虑存在数据库,因为通过数据库查询获取十分消耗资源与时间,故需将数据存储在服务 ...

  9. (转)session、cookie与“记住我的登录状态”的功能的实现

    Cookie的机制 Cookie是浏览器(User Agent)访问一些网站后,这些网站存放在客户端的一组数据,用于使网站等跟踪用户,实现用户自定义功能. Cookie的Domain和Path属性标识 ...

  10. PHP实现手机号码中间四位用星号(*)隐藏的自定义函数分享

    php屏蔽电话号码中间四位: Method 1: function hidtel($phone){ $IsWhat = preg_match('/(0[0-9]{2,3}[\-]?[2-9][0-9] ...