C#中Datatable和List互相转换
其实早就该写的,哈哈,不过今天刚想起来注册,热热手,就写一下,哈哈。
直接上内容吧:
建立一个控制台应用程序,
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互相转换的更多相关文章
- SQL Server中提前找到隐式转换提升性能的办法
http://www.cnblogs.com/shanksgao/p/4254942.html 高兄这篇文章很好的谈论了由于数据隐式转换造成执行计划不准确,从而造成了死锁.那如果在事情出现之前 ...
- 怎么实现ZBrush 4R7中界面视窗的快速转换
本篇教程介绍ZBrush® 4R7界面的基本操作之转换界面视窗, 教程属于入门教程可以帮助新手快速入门.因为ZBrush工 作界面不同于其他我们所熟知的3D软件,初次接触ZBrush的时候难免会有所困 ...
- C#中DataTable中的Compute方法使用收集
原文: C#中DataTable中的Compute方法使用收集 Compute函数的参数就两个:Expression,和Filter. Expresstion是计算表达式,关于Expression的详 ...
- C#中DataTable排序、检索、合并等操作实例
转载引用至:http://www.jb51.net/article/49222.htm 一.排序1.获取DataTable的默认视图2.对视图设置排序表达式3.用排序后的视图导出的新DataT ...
- Java中数据类型及其之间的转换
Java中数据类型及其之间的转换 基本的数据类型 基本类型有以下四种:1)int长度数据类型有:byte(8bits).short(16bits).int(32bits).long(64bits).2 ...
- ArcGIS中的坐标系定义与转换 (转载)
原文:ArcGIS中的坐标系定义与转换 (转载) 1.基准面概念: GIS中的坐标系定义由基准面和地图投影两组参数确定,而基准面的定义则由特定椭球体及其对应的转换参数确定,因此欲正确定义GIS系统坐 ...
- ArcGIS中利用ArcMap将地理坐标系转换成投影坐标系(从WKID=4326到WKID=102100)
原文:ArcGIS中利用ArcMap将地理坐标系转换成投影坐标系(从WKID=4326到WKID=102100) 对于非地理专业的开发人员,对与这些生涩的概念,我们不一定都要了解,但是我们要理解,凡是 ...
- C# 中DataTable转成模型List
C# 中DataTable转成模型List 引入using System.Reflection; 命名空间 使用注意实体类的属性名必须和DataTable的列名一致 使用: DBList<Sto ...
- sqlserver和oracle中对全半角的转换
oracle中对全半角的转换 to_single_byte(c)转换成半角 to_multi_byte(c)转换成全角 SELECT To_single_byte('881898?71') FROM ...
随机推荐
- Nginx 常见问题解决
如果提示端口已经被占用: probably another instance of uWSGI is running on the same address (:8002). bind(): Addr ...
- Makefile 10——打造更专业的编译环境-huge项目
先手工创建几个文件目录: 接下来先创建code/foo/src目录下的Makefile: .PHONY: all clean MKDIR = mkdir RM = rm RMFLAGS = -rf C ...
- Excel TargetRange.Validation为空的
做Excel的时候遇到过TargetRange.Validation为空,赋值类似空指针一样的情况. 这样的情况,不懂Excel调试了好久,最后还知道,这个对象需要自己去定义才能够进行赋值, 这样定义 ...
- jquery获取的html元素和document获取的元素的区别
最近通过ocx做了一个视频插件,然后将插件放到html中(想知道的可以看一下) 因为我要操作这个插件,要播放,停止等,所以我需要获取这个元素,不出意外的,我就用jquery来获取,然后根本无法执行,然 ...
- Softmax回归推导过程
http://www.cnblogs.com/Deep-Learning/p/7073744.html http://www.cnblogs.com/lutingting/p/4768882.html ...
- 微服务vs传统开发
使用微服务有一段时间了,这种开发模式和传统的开发模式对比,有很大的不同. 分工不同,以前我们可能是一个一个模块,现在可能是一人一个系统. 架构不同,服务的拆分是一个技术含量很高的问题,拆分是否合理对以 ...
- 5.3 SpEL语法
SqEL是一个可以独立于spring的表达式语言,即它可以用在XML中对语法进行简化 5.3 SpEL语法5.3.1 基本表达式一.字面量表达式: SpEL支持的字面量包括:字符串.数字类型(int. ...
- bootstrap基础学习一篇
官网:http://www.bootcss.com/ 这里,主要讲解bootstrap3.关于他的介绍就不用复述了. 1.示例 <!doctype html> <html lang= ...
- ANSI、ASCII、GB2312、GBK
ASCII 在计算机中,所有的数据在存储和运算时都要使用二进制数表示(因为计算机用高电平和低电平分别表示1和0),例如,像a.b.c.d这样的52个字母(包括大写).以及0.1等数字还有一些常用的符号 ...
- SQL 语句快速参考
来自 W3CSchool 的 SQL 快速参考 SQL 语句 语法 AND / OR SELECT column_name(s)FROM table_nameWHERE conditionAND|OR ...