我用的将集合类转换为DataTable 的方法

        /// <summary>
/// 将集合类转换成DataTable
/// </summary>
/// <param name="list">集合</param>
/// <returns></returns>
private static DataTable ToDataTableTow(IList list)
{
DataTable result = new DataTable();
if (list.Count > )
{
PropertyInfo[] propertys = list[].GetType().GetProperties(); foreach (PropertyInfo pi in propertys)
{
result.Columns.Add(pi.Name, pi.PropertyType);
}
foreach (object t in list)
{
ArrayList tempList = new ArrayList();
foreach (PropertyInfo pi in propertys)
{
object obj = pi.GetValue(t, null);
tempList.Add(obj);
}
object[] array = tempList.ToArray();
result.LoadDataRow(array, true);
}
}
return result;
}

将DataTable转换为List<T>

  

    /// <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) != -) 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>
/// <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 /// </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 > )
{
PropertyInfo[] propertys = list[].GetType().GetProperties();
foreach (PropertyInfo pi in propertys)
{
if (propertyNameList.Count == )
{
result.Columns.Add(pi.Name, pi.PropertyType);
}
else
{
if (propertyNameList.Contains(pi.Name))
result.Columns.Add(pi.Name, pi.PropertyType);
}
} for (int i = ; i < list.Count; i++)
{
ArrayList tempList = new ArrayList();
foreach (PropertyInfo pi in propertys)
{
if (propertyNameList.Count == )
{
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<T> 和DataTable的相互转换的更多相关文章

  1. Newtonsoft.Json 与 DataTable的相互转换

    1.这里下载:http://www.newtonsoft.com/products/json/ 安装:    解压下载文件,得到Newtonsoft.Json.dll    在项目中添加引用 2.引入 ...

  2. List,泛型和Datatable 的相互转换

    public static DataTable ToDataTableTow(IList list) { DataTable result = new DataTable(); ) { Propert ...

  3. C# List和DataTable的相互转换

    1.List转DataTable /// <summary> /// list to datatable /// </summary> /// <typeparam na ...

  4. CollatingOfData 之 JsonHelper

    1 using System; using System.Collections.Generic; using System.Linq; using System.Web; using System. ...

  5. DataTable数据与Excel表格的相互转换

    using Excel = Microsoft.Office.Interop.Excel; private static Excel.Application m_xlApp = null; /// & ...

  6. C#中DataTable与XML格式的相互转换

    1.DataTable转换成XML public string ConvertDataTableToXML(DataTable xmlDS) { MemoryStream stream = null; ...

  7. DataTable与List的相互转换

    List转DataTable: public static DataTable ToDataTable<T>(IEnumerable<T> collection) { var ...

  8. DataTable和Json的相互转换

    1 #region DataTable 转换为Json字符串实例方法 2 /// <summary> 3 /// GetClassTypeJosn 的摘要说明 4 /// </sum ...

  9. DataTable / DataSet 与 xml 的相互转换

    之前做DataTable和DataSet转xml一直使用XmlSerializer 序列化完成.今天发现新方法,哇咔咔方便了很多.还不用担心Name为空时报错 static void Main(str ...

随机推荐

  1. RJ45口线序的理解

    RJ45线序就是TX_P / TX_N / RX_P / RX_N 四根线,分别用到的是1,2,3,6 因为TX要匹配RX,所以 线1 变成 另一端的 线3, 线2 变成 另一端的 线6 反过来也一样

  2. Android Studio下打jar包

    在我们使用Eclipse时,我们常常使用的第三方类库文件大多都是jar包形式,用起来很方便.但是jar包只能打包class文件,对于Android UI类库而言,我们常常需要打包资源文件,对于界面不多 ...

  3. Android 系统移植与驱动开发--第二章搭建Android环境核心步骤及心得

    第二章 搭建Android 开发环境 虽然在这一章中讲的是Android底层开发环境,但是相应伴随的还有Android NDK程序来测试Linux驱动,HAL程序库.底层开发不仅需要交叉编译环境,还要 ...

  4. IDisposable 接口2

    定义一种释放分配的资源的方法. 命名空间:  System程序集:  mscorlib(在 mscorlib.dll 中) 语法 C# C++ F# VB [ComVisibleAttribute(t ...

  5. iOS关于sqlite3操作

    原文:http://hi.baidu.com/clickto/blog/item/0c6904f787c34125720eec87.html iPhone中支持通过sqlite3来访问iPhone本地 ...

  6. Qt远程机开发时光标注意问题

    最近项目中有一个比较奇怪的问题,就是当记录了最后的m_lastPos为当前widget中间位置之后,设置了QCursor也为当前中间位置. 这个时候当开始移动的时候,发现offset出现了很怪的极大值 ...

  7. Jquery练手之-贪吃蛇

    记得以前刚出来工作的时候,什么都不懂.老板让用Jquery写一个功能,我不会写,然后跟老板说,我就是个.net程序员,为什么要写Jquery...后面我们老大给我写了!现在我才知道net程序员要会多少 ...

  8. Tomcat安装阿里云免费证书

    安装证书 Tomcat支持JKS格式证书,从Tomcat7开始也支持PFX格式证书,两种证书格式任选其一.下载包中包含PFX格式证书和密码文件. 1.PFX证书安装 找到安装 Tomcat 目录下该文 ...

  9. html a标签

    <a> 标签定义超链接,用于从一张页面链接到另一张页面. <a> 元素最重要的属性是 href 属性,它指示链接的目标. 在所有浏览器中,链接的默认外观是: 未被访问的链接带有 ...

  10. mysql中explain优化分析

    效率比较  range >index  > all