csharp:Conversion Between DataTable and List
/// <summary>
/// http://www.codeproject.com/Tips/784090/Conversion-Between-DataTable-and-List-in-Csharp
/// </summary>
public static class ExtensionUtility
{ /// <summary>
/// Converts List To DataTable
/// </summary>
/// <typeparam name="TSource"></typeparam>
/// <param name="data"></param>
/// <returns></returns>
public static DataTable ToDataTable<TSource>(this IList<TSource> data)
{
DataTable dataTable = new DataTable(typeof(TSource).Name);
PropertyInfo[] props = typeof(TSource).GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (PropertyInfo prop in props)
{
dataTable.Columns.Add(prop.Name, Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType);
} foreach (TSource item in data)
{
var values = new object[props.Length];
for (int i = 0; i < props.Length; i++)
{
values[i] = props[i].GetValue(item, null);
}
dataTable.Rows.Add(values);
}
return dataTable;
} /// <summary>
/// Converts DataTable To List
/// </summary>
/// <typeparam name="TSource"></typeparam>
/// <param name="dataTable"></param>
/// <returns></returns>
public static List<TSource> ToList<TSource>(this DataTable dataTable) where TSource : new()
{
var dataList = new List<TSource>(); const BindingFlags flags = BindingFlags.Public | BindingFlags.Instance | BindingFlags.NonPublic;
var objFieldNames = (from PropertyInfo aProp in typeof(TSource).GetProperties(flags)
select new { Name = aProp.Name, Type = Nullable.GetUnderlyingType(aProp.PropertyType) ?? aProp.PropertyType }).ToList();
var dataTblFieldNames = (from DataColumn aHeader in dataTable.Columns
select new { Name = aHeader.ColumnName, Type = aHeader.DataType }).ToList();
var commonFields = objFieldNames.Intersect(dataTblFieldNames).ToList(); foreach (DataRow dataRow in dataTable.AsEnumerable().ToList())
{
var aTSource = new TSource();
foreach (var aField in commonFields)
{
PropertyInfo propertyInfos = aTSource.GetType().GetProperty(aField.Name);
var value = (dataRow[aField.Name] == DBNull.Value) ? null : dataRow[aField.Name]; //if database field is nullable
propertyInfos.SetValue(aTSource, value, null);
}
dataList.Add(aTSource);
}
return dataList;
}
}
测试数据源:
public class Student
{
public long Id { get; set; }
public string Name { get; set; }
public short Age { get; set; }
public DateTime DateOfCreation { get; set; }
public bool? IsActive { get; set; }
} public class Teacher
{
public long Id { get; set; }
public string Name { get; set; }
public Nullable<int> DepartmentId { get; set; }
} public class Data
{
public static List<Student> GetStudents()
{
var list = new List<Student>
{
new Student {Id = 1, Name = "Smith", Age = 18, DateOfCreation = DateTime.Now, IsActive = true},
new Student {Id = 2, Name = "Hook", Age = 16, DateOfCreation = DateTime.Now.AddDays(-1), IsActive = true},
new Student {Id = 3, Name = "Jhon", Age = 15, DateOfCreation = DateTime.Now.AddDays(-2), IsActive = true},
new Student {Id = 4, Name = "Alan", Age = 21, DateOfCreation = DateTime.Now.AddDays(-3), IsActive = true}
};
return list;
} public static List<Teacher> GetTeachers()
{
var list = new List<Teacher>
{
new Teacher {Id = 1, Name = "Smith", DepartmentId = 18 },
new Teacher {Id = 2, Name = "Hook", DepartmentId = 16 },
new Teacher {Id = 3, Name = "Jhon", DepartmentId = 15 },
new Teacher {Id = 4, Name = "Alan", DepartmentId = 21 }
};
return list;
} public static DataTable DbNullInt()
{
DataTable table = new DataTable();
table.Columns.Add("Id", typeof(long));
table.Columns.Add("Name", typeof(string)); DataColumn column;
column = new DataColumn("DepartmentId", System.Type.GetType("System.Int32"));
column.AllowDBNull = true;
table.Columns.Add(column); table.Rows.Add(1, "Smith", DBNull.Value);
table.Rows.Add(2, "Hook", 1); return table;
}
}
测试:
List<Student> students = Data.GetStudents();
/*List to DataTable conversion*/
DataTable studentTbl = students.ToDataTable();
/*DataTable to List conversion*/
List<Student> newStudents = studentTbl.ToList<Student>();//ExtensionUtility.ToList<Student>(newStudents);
this.dataGridView1.DataSource = newStudents; /*List to DataTable conversion*/
DataTable teacherTbl = Data.DbNullInt();
/*DataTable to List conversion*/
List<Teacher> newTeachers = teacherTbl.ToList<Teacher>(); this.dataGridView2.DataSource = newTeachers;
csharp:Conversion Between DataTable and List的更多相关文章
- Conversion Between DataTable and List in C#
1.List to DataTable public static DataTable ToDataTable<TSource>(this IList<TSource> dat ...
- Dapper 的输出参数使用示范
-- 普通SQL 示范-- Queries with output parameters. Hide Shrink Copy Code // output parameters // the para ...
- csharp: Export DataTable to Excel using OpenXml 2.5 in asp.net
//https://www.microsoft.com/en-us/download/details.aspx?id=5124 Open XML SDK 2.0 for Microsoft Offic ...
- csharp: DataTable Rename ColumnName and remove Column
enum ChangeNume { /// <summary> /// 简体 /// </summary> gbk=1, /// <summary> /// 英文 ...
- csharp: sum columns or rows in a dataTable
DataTable dt = setData(); // Sum rows. //foreach (DataRow row in dt.Rows) //{ // int rowTotal = 0; / ...
- CSharp 案例:用 Dynamic 来解决 DataTable 数值累加问题
需求说明 给定一个 DataTable,如果从中取出数值类型列的值并对其累加? 限制:不知该列是何种数值类型. 解决方案 1.将表转换为 IEnumerable<dynamic>,而后获取 ...
- csharp: datatable get Column datatype or Column Name
/// <summary> ///列表名 /// </summary> /// <param name="table"></param&g ...
- csharp: DataTable export to excel,word,csv etc
http://code.msdn.microsoft.com/office/Export-GridView-to-07c9f836 https://exporter.codeplex.com/ htt ...
- csharp: DataTable结构相同的比较
) ) * pageSize; ; i++) { DataRow newdr = newdt.NewRow(); DataRow dr = dt.Rows[i]; foreach (Dat ...
随机推荐
- 河内塔问题(C++版)
上次,我们讲了汉诺塔,今天我们来讲一讲和汉诺塔类似的题目<河内塔问题> 题目描述 Description 一位法国数学家曾编写过一个印度的古老传说:在世界中心贝拿勒斯(在印度北部)的圣庙里 ...
- Oracle数据库学习(一):虚拟机下Oracle Linux的安装与配置
这篇博文主要以图片的形式讲述Oracle Linux在虚拟机下的安装与配置 一.前期虚拟机安装ISO文件的配置 1.创建新的虚拟机 2.选择“自定义(高级)”选项,下一步,默认“虚拟机硬件兼容性”或选 ...
- JAVA数据结构--Array数组实现
所谓数组,是有序的元素序列. [1] 若将有限个类型相同的变量的集合命名,那么这个名称为数组名.组成数组的各个变量称为数组的分量,也称为数组的元素,有时也称为下标变量.用于区分数组的各个元素的数字编 ...
- 插播一条 QQ头像无法正常显示问题
问题背景 不知道啥什么,QQ群的头像有些显示不全直接是默认的头像.想一想最近也没做啥,怎么就出问题了. 后来想一想,大概是个人文件夹的文件出问题了 解决办法 好友头像显示问题的删除 MiscHead. ...
- JS框架设计之对象扩展一种子模块
对象扩展 说完了,对象的创建(框架的命名空间的创建)以及如何解决多库之间的命名空间冲突问题之后,接下来,就是要扩展我们的对象,来对框架进行扩展,我们需要一种新功能,将新添加的功能整合到我们定义的对象中 ...
- AngularJS指令详解
一.什么是指令? 在<AngularJs权威教程>中,指令可以简单理解成特定的DOM元素上运行的函数:我认为还可以理解成将将自定义的HTML标签解析成原始的标签,然后为其加入一些扩展的功能 ...
- 数据库~Mysql里的Explain说明
对于mysql的执行计划可以在select前添加Explain来实现,它可以告诉我们你的语句性能如何. 下面是对explain的具体说明,也都是官方的,以后进行参考. id SELECT识别符.这是S ...
- hr中间插入字体
修饰CSS:hr:before { content: "??";} hr:after { content: " This is an <hr> element ...
- MySQL数据库以及其Python用法
一 命令行模式下: mysql -u root -p # 进入进入mysql命令行模式 show databases; # 查看所有数据库 create database data; # 创建数据库, ...
- springboot-3-aop
aop存在的目的是进一步解耦, spring支持aspectJ的注解式切面编程 1), 使用@Aspect声明为一个切面, 并使用@Component加入context中 2), 使用@After, ...