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 ...
随机推荐
- 定位布局—position
1. position的属性 1.1position:static 默认位置,没有定位效果 1.2 position:relative 相对定位,不会脱离文档流,相对于原来位置的变化 <!DOC ...
- 【Hive】数据类型
1.基本类型 整型:tinyint / samllint / int / bigint 浮点型:float / double / Decimals 布尔型:boolean 字符串:string / v ...
- 封装hibernate中session(静态单例模式)
因为每次用增删改查时都需要用到session,直接做一个类,需要的时候只需要调用即可 import org.hibernate.Session; import org.hibernate.Sessio ...
- git pull VS git fetch&merge
使用git fetch和git pull都可以更新远程仓库的代码到本地,但是它们之间还是有区别. git fetch git fetch origin master git log -p maste ...
- List列表按照对象进行排序
在某些业务场景下需要根据list列表中对象的字段进行排序.今天就以实例说明: 实体类 public class Product { private int discount; // 省略getter/ ...
- Ubuntu下搭建WordPress环境
WordPress是一种使用PHP语言开发的博客平台,用户可以在支持PHP和MySQL数据库的服务器上架设属于自己的网站.也可以把 WordPress当作一个内容管理系统(CMS)来使用.WordPr ...
- linux, windows, mac, ios等平台GCC预编译宏判断
写跨平台c/c++程序的时候,需要搞清各平台下面的预编译宏,区分各平台代码.而跨平台c/c++编程,GCC基本在各平台都可以使用.整理了一份各平台预编译宏的判断示例. 需要注意几点: * window ...
- Django 碎片集合
命令行创建Django项目 熟记建立django命令:django-admin startproject xx (start project) 目录介绍 manage.py 文件是用来管理文件 ...
- MySQL FEDERATED 存储引擎的使用
FEDERATED 存储引擎描述 FEDERATED存储引擎能让你访问远程的MySQL数据库而不使用replication或cluster技术(类似于Oracle的dblink),使用FEDERATE ...
- The last packet sent successfully to the server was 0 milliseconds ago
出现异常”The last packet sent successfully to the server was 0 milliseconds ago.“的大部分原因是由于数据库回收了连接,而系统的缓 ...