DataTableHelper.cs 将DataTable转换为List,将List转换为DataTable的实现类
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks; namespace Xmh.DBUnit
{
/// <summary>
/// 将DataTable转换为List,将List转换为DataTable的实现类
/// </summary>
public static class DataTableHelper
{
public static DataTable ConvertTo<T>(IList<T> list)
{
DataTable table = CreateTable<T>();
Type entityType = typeof(T);
PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(entityType);
foreach (T item in list)
{
DataRow row = table.NewRow();
foreach (PropertyDescriptor prop in properties)
row[prop.Name] = prop.GetValue(item);
table.Rows.Add(row);
}
return table;
} 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 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);
} //Convert DataRow into T Object
public static T CreateItem<T>(DataRow row)
{
string columnName;
T obj = default(T);
if (row != null)
{
obj = Activator.CreateInstance<T>();
foreach (DataColumn column in row.Table.Columns)
{
columnName = column.ColumnName;
//Get property with same columnName
PropertyInfo prop = obj.GetType().GetProperty(columnName); try
{
Type type = prop.PropertyType;
//判断type类型是否为泛型,因为nullable是泛型类,
if (type.IsGenericType && type.GetGenericTypeDefinition().Equals(typeof(Nullable<>)))//判断convertsionType是否为nullable泛型类 {
//如果type为nullable类,声明一个NullableConverter类,该类提供从Nullable类到基础基元类型的转换
System.ComponentModel.NullableConverter nullableConverter = new System.ComponentModel.NullableConverter(type);
//将type转换为nullable对的基础基元类型
type = nullableConverter.UnderlyingType;
}
//Get value for the column
object value = (row[columnName].GetType() == typeof(DBNull))
? null : row[columnName];
//Set property value
if (prop.CanWrite) //判断其是否可写
prop.SetValue(obj, (value == null ? null : Convert.ChangeType(value, type)), null);
}
catch
{
throw;
//Catch whatever here
}
}
}
return obj;
} public static DataTable CreateTable<T>()
{
Type entityType = typeof(T);
DataTable table = new DataTable(entityType.Name);
PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(entityType); foreach (PropertyDescriptor prop in properties)
table.Columns.Add(prop.Name, prop.PropertyType); return table;
} public static List<T> ToList<T>(this DataTable dt) where T : class, new()
{
Type t = typeof(T);
PropertyInfo[] propertys = t.GetProperties();
List<T> lst = new List<T>();
string typeName = string.Empty;
foreach (DataRow dr in dt.Rows)
{
T entity = new T();
foreach (PropertyInfo pi in propertys)
{
typeName = pi.Name;
if (dt.Columns.Contains(typeName))
{
if (!pi.CanWrite) continue;
object value = dr[typeName];
if (value == DBNull.Value) continue;
if (pi.PropertyType == typeof(string))
{
pi.SetValue(entity, value.ToString(), null);
}
else if (pi.PropertyType == typeof(int) || pi.PropertyType == typeof(int?))
{
pi.SetValue(entity, int.Parse(value.ToString()), null);
}
else if (pi.PropertyType == typeof(DateTime?) || pi.PropertyType == typeof(DateTime))
{
pi.SetValue(entity, DateTime.Parse(value.ToString()), null);
}
else if (pi.PropertyType == typeof(float))
{
pi.SetValue(entity, float.Parse(value.ToString()), null);
}
else if (pi.PropertyType == typeof(double))
{
pi.SetValue(entity, double.Parse(value.ToString()), null);
}
else
{
pi.SetValue(entity, value, null);
}
}
}
lst.Add(entity);
}
return lst;
}
}
}
DataTableHelper.cs 将DataTable转换为List,将List转换为DataTable的实现类的更多相关文章
- LINQ返回DataTable类型 list转dataset 转换为JSON对象
using System.Web.Script.Serialization; using System.Collections.Generic; using System.Reflection; us ...
- C#之DataTable转List与List转Datatable
闲来无事,只有写代码啦,以下为DataTable转List与List转DataTable的两个方法,主要技术点用到了反射原理: /// <summary> /// 模型转换类 /// &l ...
- C# DataTable转List And List转DataTable
// DataTable转List: IList<HousesEntity> Ilist = TableAndList.ConvertTo<HousesEntity>(dt); ...
- “DataTable”是“System.Data.DataTable”和“Microsoft.Office.Interop.Excel.DataTable”之间的不明确的引用
“DataTable”是“System.Data.DataTable”和“Microsoft.Office.Interop.Excel.DataTable”之间的不明确的引用 造成这个错误的原因是,在 ...
- 多个不同的表合并到一个datatable中,repeater在绑定datatable
using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.UI ...
- 将两个列不同的DataTable合并成一个新的DataTable
/// <summary> /// 将两个列不同(结构不同)的DataTable合并成一个新的DataTable /// </summary> ...
- EasyUI - Datatable转Json and Json转Datatable
using System; using System.Data; using System.Linq; using System.Collections; using System.Collectio ...
- DataSet转换为泛型集合和DataRow 转成 模型类
public static class TransformToList { /// <summary> /// DataSet转换为泛型集合 /// </summary> // ...
- C#给DataTable添加序号、C#给DataTable添加合计、小计
/// <summary> /// 给DataTable添加序号 /// </summary> /// <param name= ...
随机推荐
- lambda表达式与匿名内部类与双冒号(::)
lambda表达式在只有一条代码时还可以引用其他方法或构造器并自动调用,可以省略参数传递,代码更加简洁,引用方法的语法需要使用::符号.lambda表达式提供了四种引用方法和构造器的方式: 引用对象的 ...
- Python 基础 3 - 元组
元组与列表区别 Python 元组与列表类似,不同之处在于列表可以修改,元组不可以修改 元组用小括号 () 定义,列表用方括号 [] 定义 元组不可修改,列表可修改 元组创建 只需要在小括号 () 内 ...
- MySQL基础/数据库和表的设计
MySQL基础 一:安装MySQL(按步骤操作,如果下载后使用不了,试着用360安全卫士卸载MySQL,清除残留的,方便在下载造成不必要的麻烦:如果这样也不行,那就需要重做系统在进行下载) 二:创建数 ...
- ThreadPoolTaskExecutor介绍
ThreadPoolTaskExecutor是一个spring的线程池技术,其实,它的实现方式完全是使用ThreadPoolExecutor进行实现.对于ThreadPoolExecutor,有一些重 ...
- Android studio初次安装启动时弹出unable to access android sdk add-on list提示的解决方法
一.问题描述 初次安装Android Studio,启动后,报错如下: unable to access android sdk add-on lis 如图: 二.原因分析 AS启动后,会在默认路径下 ...
- Winform中实现ZedGraph曲线图的图像复制到剪切板、打印预览、获取图片并保存、另存为的功能
场景 Winforn中设置ZedGraph曲线图的属性.坐标轴属性.刻度属性: https://blog.csdn.net/BADAO_LIUMANG_QIZHI/article/details/10 ...
- ACM代码模板
功能介绍 写了I/O函数,支持以下几种方式 read(num); //读入一个数num(任意整数类型,下同) read(num1,num2,num3,num4); //读入任意多个数 read(arr ...
- java数据结构——栈(Stack)
学习数据结构与算法是枯燥的,但只有坚持不懈的积累,才会有硕果累累的明天. /** * 继续学习Java数据结构 ————栈 * 栈的实现其实还是使用数组,只不过我们不能直接访问数组下标,而是通过一个指 ...
- hadoop之mapreduce详解(基础篇)
本篇文章主要从mapreduce运行作业的过程,shuffle,以及mapreduce作业失败的容错几个方面进行详解. 一.mapreduce作业运行过程 1.1.mapreduce介绍 MapRed ...
- shell脚本一键部署lvs+keepalived
环境 两个调度器dr1.dr2,两台真实机rs1.rs2.两台真实机安装httpd,并编辑主页内容用于验证 vip="192.168.132.250"dr1="192.1 ...