我用的将集合类转换为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. memcache实现公共计数器网站

    在反问题的过程中遇到的最近项目.网上查了很多资料并没有完全实现. 因此,要找到适合自己的xmemcache client和memcache关联API和说明,我们发现了一个比较完美的实现. 键类:net ...

  2. 高效实现 std::string split() API

    Qt下一个 QString 实现split()性能.和std::string未实现它的.STL也未实现.只有自己可以写一. #include <string> #include <v ...

  3. java——递归调用

    递归函数调用调用本身,并通过自己的相应参数,这个计算过程中进行层,直到满足某些条件,只要停止呼叫. 递归函数的特点 1.函数要直接或间接调用自身. 2.要有递归终止条件检查.即递归终止的条件被满足后. ...

  4. Qt 学习之路 :访问网络(4)

    前面几章我们了解了如何使用QNetworkAccessManager 访问网络.在此基础上,我们已经实现了一个简单的查看天气的程序.在这个程序中,我们使用QNetworkAccessManager进行 ...

  5. Creating a Background Service ——IntentService

    The IntentService class provides a straightforward structure for running an operation on a single ba ...

  6. Python之路,Day14 - It's time for Django

    Python之路,Day14 - It's time for Django   本节内容 Django流程介绍 Django url Django view Django models Django ...

  7. jQuery的矿建结构小demo举例

    (function (global) { var document = global.document,//变成局部变量提高搜索的性能 init;// 核心函数 function itcast(sel ...

  8. 将sql数据库逆向生成PDM模型

    由于接手的一个项目是公司前期外包出去的,所以到手的只有繁杂的代码,和数据库文件.由于是个新手,我需要一个数据字典来帮助我完成一些东西,所以我就想到从sql数据库转换出一个pdm模型的数据字典. 第一步 ...

  9. Android开发手记(15) 拨打电话和收发短信

    1.Intent简介 Android组价之间的通信,由Intent来协助完成.Intent负责对应用中一次操作的动作.动作涉及数据.附加数据进行描述,Android则根据此Intent的描述,负责找到 ...

  10. 计时器(Chronometer)的使用

    安卓提供了一个计时器组件:Chronometer,该组件extends TextView,因此都会显示一段文本,但是它显示的时间是从某个起始时间开始过去了多少时间,它只提供了android:forma ...