List转Datatable 新方法
方法1,最简单的转换
DataTable dt = new DataTable();
dt.Columns.Add("id");
dt.Columns.Add("name");
dt.Rows.Add(new object[]{ 0,"顶层菜单"});
foreach (var cm in comdList)
{
DataRow dr = dt.NewRow();
dr["id"] = cm.SYS_COMMANDS_ID;
dr["name"] = cm.TXT_COMMANDTITLE;
dt.Rows.Add(dr);
}
方法2,建立类
public static class DataTableExtensions
{
/// <summary>
/// 转化一个DataTable
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="list"></param>
/// <returns></returns>
public static DataTable ToDataTable<T>(this IEnumerable<T> list)
{
//创建属性的集合
List<PropertyInfo> pList = new List<PropertyInfo>();
//获得反射的入口
Type type = typeof(T);
DataTable dt = new DataTable();
//把所有的public属性加入到集合 并添加DataTable的列
Array.ForEach<PropertyInfo>(type.GetProperties(), p => { pList.Add(p); dt.Columns.Add(p.Name, p.PropertyType); });
foreach (var item in list)
{
//创建一个DataRow实例
DataRow row = dt.NewRow();
//给row 赋值
pList.ForEach(p => row[p.Name] = p.GetValue(item, null));
//加入到DataTable
dt.Rows.Add(row);
}
return dt;
}
/// <summary>
/// DataTable 转换为List 集合
/// </summary>
/// <typeparam name="TResult">类型</typeparam>
/// <param name="dt">DataTable</param>
/// <returns></returns>
public static List<T> ToList<T>(this DataTable dt) where T : class, new()
{
//创建一个属性的列表
List<PropertyInfo> prlist = new List<PropertyInfo>();
//获取TResult的类型实例 反射的入口
Type t = typeof(T);
//获得TResult 的所有的Public 属性 并找出TResult属性和DataTable的列名称相同的属性(PropertyInfo) 并加入到属性列表
Array.ForEach<PropertyInfo>(t.GetProperties(), p => { if (dt.Columns.IndexOf(p.Name) != -1) prlist.Add(p); });
//创建返回的集合
List<T> oblist = new List<T>();
foreach (DataRow row in dt.Rows)
{
//创建TResult的实例
T ob = new T();
//找到对应的数据 并赋值
prlist.ForEach(p => { if (row[p.Name] != DBNull.Value) p.SetValue(ob, row[p.Name], null); });
//放入到返回的集合中.
oblist.Add(ob);
}
return oblist;
}
/// <summary>
/// 将集合类转换成DataTable
/// </summary>
/// <param name="list">集合</param>
/// <returns></returns>
public static DataTable ToDataTableTow(IList list)
{
DataTable result = new DataTable();
if (list.Count > 0)
{
PropertyInfo[] propertys = list[0].GetType().GetProperties();
foreach (PropertyInfo pi in propertys)
{
result.Columns.Add(pi.Name, pi.PropertyType);
}
for (int i = 0; i < list.Count; i++)
{
ArrayList tempList = new ArrayList();
foreach (PropertyInfo pi in propertys)
{
object obj = pi.GetValue(list[i], null);
tempList.Add(obj);
}
object[] array = tempList.ToArray();
result.LoadDataRow(array, true);
}
}
return result;
}
/**/
/// <summary>
/// 将泛型集合类转换成DataTable
/// </summary>
/// <typeparam name="T">集合项类型</typeparam>
/// <param name="list">集合</param>
/// <returns>数据集(表)</returns>
public static DataTable ToDataTable<T>(IList<T> list)
{
return ToDataTable<T>(list, null);
}
/**/
/// <summary>
/// 将泛型集合类转换成DataTable
/// </summary>
/// <typeparam name="T">集合项类型</typeparam>
/// <param name="list">集合</param>
/// <param name="propertyName">需要返回的列的列名</param>
/// <returns>数据集(表)</returns>
public static DataTable ToDataTable<T>(IList<T> list, params string[] propertyName)
{
List<string> propertyNameList = new List<string>();
if (propertyName != null)
propertyNameList.AddRange(propertyName);
DataTable result = new DataTable();
if (list.Count > 0)
{
PropertyInfo[] propertys = list[0].GetType().GetProperties();
foreach (PropertyInfo pi in propertys)
{
if (propertyNameList.Count == 0)
{
if (pi.PropertyType.FullName.Contains("Nullable")) result.Columns.Add(pi.Name);
else result.Columns.Add(pi.Name, pi.PropertyType);
}
else
{
if (propertyNameList.Contains(pi.Name))
{
if (pi.PropertyType.FullName.Contains("Nullable")) result.Columns.Add(pi.Name);
else result.Columns.Add(pi.Name, pi.PropertyType);
}
}
}
for (int i = 0; i < list.Count; i++)
{
ArrayList tempList = new ArrayList();
foreach (PropertyInfo pi in propertys)
{
if (propertyNameList.Count == 0)
{
object obj = pi.GetValue(list[i], null);
tempList.Add(obj);
}
else
{
if (propertyNameList.Contains(pi.Name))
{
object obj = pi.GetValue(list[i], null);
tempList.Add(obj);
}
}
}
object[] array = tempList.ToArray();
result.LoadDataRow(array, true);
}
}
return result;
}
}
List转Datatable 新方法的更多相关文章
- C#基础课程之六(临时表)DataTable使用方法
DataTable 用法:赋取值操作,及报错情况 dataTable.Columns.Add("Name"); //Columns 对象获取该集合的全部列,添加列名. 默认stri ...
- DataTable.AcceptChanges方法有何用处
提交自上次调用 AcceptChanges 以来对该表进行的全部更改. 调用 AcceptChanges 后,再用 DataAdapter.Update() 不会有不论什么新数据被更新到数据库中.那- ...
- C# DataTable使用方法详解--删除表数据
在项目中常常常使用到DataTable,假设DataTable使用得当,不仅能使程序简洁有用,并且可以提高性能,达到事半功倍的效果,现对DataTable的使用技巧进行一下总结. 1.添加引用 1 u ...
- C#DataTable使用方法详解
在项目中常常常使用到DataTable,假设DataTable使用得当,不仅能使程序简洁有用,并且可以提高性能,达到事半功倍的效果,现对DataTable的使用技巧进行一下总结. 1.添加引用 1 2 ...
- 【C#代码实战】群蚁算法理论与实践全攻略——旅行商等路径优化问题的新方法
若干年前读研的时候,学院有一个教授,专门做群蚁算法的,很厉害,偶尔了解了一点点.感觉也是生物智能的一个体现,和遗传算法.神经网络有异曲同工之妙.只不过当时没有实际需求学习,所以没去研究.最近有一个这样 ...
- 遍历datatable的方法汇总
遍历datatable的方法方法一: DataTable dt = dataSet.Tables[]; ; i < dt.Rows.Count ; i++) { string strName = ...
- 【Android】一种提高Android应用进程存活率新方法
[Android]一种提高Android应用进程存活率新方法 SkySeraph Jun. 19st 2016 Email:skyseraph00@163.com 更多精彩请直接访问SkySeraph ...
- Execel(导出新方法):
#region 新方法 //var sbHtml = new StringBuilder(); //sbHtml.Append("<table border='1' cellspaci ...
- 交换ctrl和caps_loack的新方法
交换ctrl和caps_loack的新方法 Table of Contents 1 过程 1 过程 debian用了几年,由于emacs的关系,一直将右ctrl和caps_lock键交换,使用的是xm ...
随机推荐
- windows平台下安装Beautiful Soup
1.Beautiful Soup 4.3.2 下载 2.下载完成后解压,放在Python的安装目录下,假设放到C:/Python 3.运行cmd,切换到C:/Python/Beautiful Soup ...
- oracle索引-二元高度
本文转载 作为数据库管理员来说,要在表上建立索引很简单.但是要知道这个索引是否合适.如何优化索引则就具有一定的难度.这项工作也是用来评价一个数据库管理员是否算得上专家的一个重要指标.那么为什么索引优化 ...
- 注册表操作的几个windows api
(转自:http://blog.sina.com.cn/s/blog_4e66c6cd01000bcu.html) 键管理类: RegCloseKey():关闭注册表键释放句柄. RegC ...
- Struts01---入门小案例
创建web项目 实现的效果! 用户点击页面不同的链接,后台调用不同的代码! 创建两个类实现共同的接口! public interface Action { String execute(); } ...
- PostgreSQL日志配置记录
日志审计 审计是值记录用户的登陆退出以及登陆后在数据库里的行为操作,可以根据安全等级不一样设置不一样级别的审计, 此处涉及的参数文件有: logging_collector --是否开启日 ...
- Js事件处理模型/周期
有3个阶段 1. 捕获阶段:由外向内,记录各级父元素上绑定的事件处理函数---只记录,不触发. 2. 目标触发:优先触发目标元素上的事件处理函数. 3. 冒泡:由内向外,按捕获的顺序的相反的方向 ...
- Creating a Game with CocosBuilder
Creating a Game with CocosBuilder This tutorial aims to show how you can use CocosBuilder together w ...
- 大白话讲解如何给github上项目贡献代码
本文献给对git很迷茫的新手,注意是新手,但至少会点基本操作,有点基本概念的新手,我不会从怎么用github和git是什么开始讲的.如果作为新手你看书又看不进去,原理又太复杂,又没有直接了当告诉我们怎 ...
- 安装PL/SQL客户端来访问操作步骤
1 2 3.改变路径 4 5 6 7 8 9.选择注册机 10
- bzoj 4987 Tree
Written with StackEdit. Description 从前有棵树. 找出\(K\)个点\(A_1,A_2,-,A_K\). 使得\(∑dis(A_i,A_{i+1}),(1<= ...