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 ...
随机推荐
- 1.HTML练习(二)
一.表格练习: 1.<table>标签:声明一个表格,它的常用属性如下: border属性 定义表格的边框,设置值是数值 cellpadding属性 定义单 ...
- 构造函数详解,explicit,初始化列表
一.构造函数 在类中有一种特殊的成员函数,它的名字与类名相同,我们在创建类的时候,这个特殊的成员函数就会被系统调用.这个成员函数,就叫“构造函数”. 因为构造函数会被系统自动调动,构造函数的目的就是初 ...
- 一次完整的http请求全程
当我们在打开浏览器的时候,在地址栏输入诸如 http://www.baidu.com时,几秒后浏览器打开百度页面,几秒钟内到底发生了哪些事情. 一.解析URL: 浏览器首先会对输入的URL进行检查,如 ...
- 图的最小生成树的理解和实现:Prim和Kruskal算法
最小生成树 一个连通图的生成树是一个极小的连通子图,它含有图中所有的顶点,但只有足以构成一棵树的n-1条边.我们将构造连通网的最小代价生成树称为最小生成树(Minimum Cost Spanning ...
- 汉诺塔的python 动画演示
1.简介 古代有一座汉诺塔,塔内有3个座A.B.C,A座上有n个盘子,盘子大小不等,大的在下,小的在上,如图所示.有一个和尚想把这n个盘子从A座移到C座,但每次只能移动一个盘子,并且自移动过程中,3个 ...
- WC2019退役记
sb题不会,暴力写不完,被全场吊着打,AFO
- 区间DP的学习(持续更新)
例题: 1.Multiplication Puzzle 原题地址:http://poj.org/problem?id=1651 2.Dire Wolf 原题地址:http://acm.split.hd ...
- MySQL自定义排序
存在表A 按名字倒序排 SELECT * FROM A ORDER BY name DESC 结果如下: 若需要按照王五.张三.李四的顺序排序,使用自定义排序:FIELD() SELEC ...
- golang在gitlab中的工作流
在敏捷开发的时代, 快速的编码, code review, 测试, 部署, 是提升程序员效率的关键. 同时在基础工具完备的如今, 我们甚至无需过多的操作就可以轻松实现上述步骤, 本文就以gitlab为 ...
- java反射机制_读取properties
代码: import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; /** * 反射特点: ...