Conversion Between DataTable and List in C#
2016-05-04 23:50
976 查看
1.List to DataTable
2.DataTable To List
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; }
2.DataTable To List
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; }
相关文章推荐
- C#之 DataGridView 导出到Excel
- C#实现多功能播放器
- C#实现鼠标的自动循环指定操作
- C#获取文件夹下所有的子文件
- C# socket连接断开问题
- C#学习笔记之string
- [学习笔记]C#中使用EmguCv时出现的 “Emgu.CV.CvInvoke”的类型初始值设定项引发异常
- C#的未来:元组及匿名结构体
- C#中Dictionary的作用及用法讲解
- VS C#项目 debug目录下的各文件作用
- C# AttributeUsage的使用浅析
- C#基础系列之第一弹:语言规范
- c# 中基类变量指向派生类对象的实例化
- 粒子圆圈效果
- C# XCOPY命令 预先生成事件命令行”和“后期生成事件命令行”
- c#生成方案里预生成拷贝文件
- 第二十课先乘除后加减——C#计算器编程教学
- C# 动态修改Config
- C# Winform的简易聊天程序
- C#图片切割、图片压缩、缩略图生成代码汇总