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

  直接上内容吧:

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

             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. C++-教程1-VS2010环境设置

    一.需要下载的软件 1.visual studio 2010\\xxzx\tools\编程工具\MICROSOFT\VISUAL.STUDIO\VISUAL.STUDIO.201032位cn_visu ...

  2. SQLite的连接字符串

    SQLite的连接字符串 Basic(基本的)     Data Source=filename;Version=3;Using UTF16(使用UTF16编码)    Data Source=fil ...

  3. 跟着百度学PHP[13]-文件上传

    PS:上传的时候一定要用POST方法,GET方法不行. 文件上传的entype要改成“mutilpart/form-data”这个编码 <html> <form action=&qu ...

  4. 跟着百度学PHP[9]-session会话

    参考:http://www.w3school.com.cn/php/php_sessions.asp session变量用于存储有关用户的会话的信息,或更改用户会话的设置,session变量保存的信息 ...

  5. 读取大csv文件数据插入到MySql或者Oracle数据库通用处理

    import java.io.BufferedInputStream; import java.io.BufferedReader;import java.io.BufferedWriter;impo ...

  6. java----Servlet的生命周期

    Servlet生命周期分为三个阶段: 1,初始化阶段  调用init()方法 2,响应客户请求阶段 调用service()方法 3,终止阶段 调用destroy()方法 Servlet初始化阶段: 在 ...

  7. QWidget切换

    QWidget切换,参考类:QstackedLayout,QStackedWidget,QTabWidget 一.Tab出现的位置 tabWidget.setTabPosition(QTabWidge ...

  8. 【Debian】时间设置

    http://blog.linuxphp.org/archives/567/ http://www.dedecms.com/knowledge/servers/linux-bsd/2012/0819/ ...

  9. freemarker3

    结束标签 可以在结束标签中忽略user_def_dir_exp 也就是说可以写</@>来代替</@anything> 循环变量 <@myRepeatMacro count ...

  10. zoj 3362(最大费用)

    题目链接:http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemId=3904 思路:费用流的题,增加一个超级源点和一个超级汇点,然后就是连边 ...