方法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 新方法的更多相关文章

  1. C#基础课程之六(临时表)DataTable使用方法

    DataTable 用法:赋取值操作,及报错情况 dataTable.Columns.Add("Name"); //Columns 对象获取该集合的全部列,添加列名. 默认stri ...

  2. DataTable.AcceptChanges方法有何用处

    提交自上次调用 AcceptChanges 以来对该表进行的全部更改. 调用 AcceptChanges 后,再用 DataAdapter.Update() 不会有不论什么新数据被更新到数据库中.那- ...

  3. C# DataTable使用方法详解--删除表数据

    在项目中常常常使用到DataTable,假设DataTable使用得当,不仅能使程序简洁有用,并且可以提高性能,达到事半功倍的效果,现对DataTable的使用技巧进行一下总结. 1.添加引用 1 u ...

  4. C#DataTable使用方法详解

    在项目中常常常使用到DataTable,假设DataTable使用得当,不仅能使程序简洁有用,并且可以提高性能,达到事半功倍的效果,现对DataTable的使用技巧进行一下总结. 1.添加引用 1 2 ...

  5. 【C#代码实战】群蚁算法理论与实践全攻略——旅行商等路径优化问题的新方法

    若干年前读研的时候,学院有一个教授,专门做群蚁算法的,很厉害,偶尔了解了一点点.感觉也是生物智能的一个体现,和遗传算法.神经网络有异曲同工之妙.只不过当时没有实际需求学习,所以没去研究.最近有一个这样 ...

  6. 遍历datatable的方法汇总

    遍历datatable的方法方法一: DataTable dt = dataSet.Tables[]; ; i < dt.Rows.Count ; i++) { string strName = ...

  7. 【Android】一种提高Android应用进程存活率新方法

    [Android]一种提高Android应用进程存活率新方法 SkySeraph Jun. 19st 2016 Email:skyseraph00@163.com 更多精彩请直接访问SkySeraph ...

  8. Execel(导出新方法):

    #region 新方法 //var sbHtml = new StringBuilder(); //sbHtml.Append("<table border='1' cellspaci ...

  9. 交换ctrl和caps_loack的新方法

    交换ctrl和caps_loack的新方法 Table of Contents 1 过程 1 过程 debian用了几年,由于emacs的关系,一直将右ctrl和caps_lock键交换,使用的是xm ...

随机推荐

  1. C#和Java接口对比

    C#和java的接口有很多类似之处,对于编程约束和设计模式的实现有重要作用.这里记录几个知识点. 1. C#的接口中不能有字段,但Java的接口中允许有static final修饰的字段/域(fiel ...

  2. 51nod 1154 dp

    http://www.51nod.com/onlineJudge/questionCode.html#!problemId=1154 1154 回文串划分 基准时间限制:1 秒 空间限制:131072 ...

  3. JSON.parse()和JSON.stringify()以及stringify()字符串格式化

    1. parse用于从一个字符串中解析出json对象,如var str = '{"name":"huangxiaojian","age":& ...

  4. css中zoom:1以及z-index的作用

    一.CSS中zoom:1的作用在做IE6.IE7.IE8浏览器兼容的时候,经常会遇到一些问题,可以使用zoom:1来解决,有如下作用:1.触发IE浏览器的haslayout2.解决IE下的浮动,mar ...

  5. C#学习历程(二)[基础知识]

    c#中类型的转换 1.Convert.ToInt32(string s) 这个方法的返回值是int类型,要用int类型的变量接收 如: string strNum=Console.ReadLine() ...

  6. poi自定义颜色设置(转)

    原文链接  http://javapolo.iteye.com/blog/1604501 最近在项目的开发中使用到了apache poi,该组件可以让我们方便的操作excell,该工具非常容易上手,但 ...

  7. Java基本数据对应的封装类

    Java基本数据对应的封装类 在java中一切都是以类为基础的,并且java对基本的数据类型也进行了封装,如下所示,将介绍几个基本的数据类型及其封装类: 1 Boolean VS boolean pu ...

  8. [置顶] Android Shape一些新玩法?

    敏少咨讯: 1.生活琐事篇 最近由于公司赶项目所以偷懒了,博客没有及时更新,还请小伙伴们手下留情啊!最近发生了很多趣事,就在今天我们学校退书籍费,这可把我开心的哈哈!无缘无故又有钱了,嘿嘿,刚好五一出 ...

  9. Kali Linux:使用nmap扫描主机

    nmap-Network Mapper,是著名的网络扫描和嗅探工具包.他同样支持Windows和OS X. 扫描开放端口和判断操作系统类型 先让我们ping一段地址范围,找到启动的主机: # nmap ...

  10. MyBatis典型的错误org.apache.ibatis.binding.BindingException: Invalid bound statement (not found)

    XXXmapper.java(接口) XXXmapper.xml(结果集映射) //此两个文件要在统一包下,且xml中的namespace是唯一的,为了区分须写成 该xml的全路径