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 ...
随机推荐
- mybatis常用默认配置
设置参数 描述 有效值 默认值 cacheEnable 该配置影响所有映射器中配置的缓存全局开关 true.false true lazyLoadingEnable 延迟加载的全局开关.当它开启时,所 ...
- 新版 iPad Pro 弯了,苹果表示这是正常现象……
简评:苹果上个月才发布的新版 iPad Pro 出问题了.有用户抱怨说,iPad 出现了机身弯曲.然而苹果公司认为这并不会影响性能,所以坚持这不是一个缺陷,emmm-- 虽然苹果公司的品控一直为人称道 ...
- 如何在Cordova Android 7.0.0 以下版本集成最新插件 极光插件为例
前提 Cordova Android 7.0.0开始改变了项目安卓平台的架构.新建一个空项目分别添加Android 6.4.0 和 Android 7.0.0平台: cordova platform ...
- 阅读Protobuf官网的一些笔记
阅读 Protobuf 官网的一些笔记 Protobuf API(The Protocol Buffer API) 每个字段都会有基本的 set_ get_ 方法 string类型的字段可以使用 mu ...
- shiro原理及其运行流程介绍
shiro原理及其运行流程介绍 认证执行流程 1.通过ini配置文件创建securityManager 2.调用subject.login方法主体提交认证,提交的token 3.securityMan ...
- 【总结】sqli-labs Less(1-35) 小结
0x00 工具 phpstudy2016:链接:http://pan.baidu.com/s/1bpbEBCj 密码:fmr4 sqli-labs-master:链接:http://pan.bai ...
- mysql只能本机访问
众所周知的是,mysql默认是listen 0.0.0.0:3306. 大网站的数据库服务器一般都在内网没有外网ip,用默认配置比较省事.但是如果只有一台vps,lnmp全部署在同一vps 上,mys ...
- IIS7如何实现访问HTTP跳转到HTTPS访问 转的
加几句,1.安装url重写模块,不需要重启IIS,安装完了就能用.个人感觉比 IIS REWRITE组件更好用,iis rewrite是安装第三方的那种,不缴费只可以把所有规则写在一起,不能区别站点, ...
- 自定义 checkbox 样式
前言:最近在做一个网站,为了统一风格,需要自定义checkbox的样式.所以花了点时间参考了 研究了一下.感觉上面的方法略微麻烦.所以自己重新写了下面的代码,欢迎大家指教.同时,感谢w3cplus提供 ...
- [问题解决]Fresco设置圆角效果不生效问题探究
[问题解决]Fresco设置圆角效果不生效问题探究 /** * Created by diql on 2017/2/21 11:07:04. */ 问题 在View中设置: fresco:rounde ...