关于DataTable与IList和List泛型集合的相互转换在网上总结

我在做amchart的还有微软相关的chart控件时发现绑定使用Datatabale不能绑定 但是支持DataSet 和泛型集合;于是谢谢网上好友的帮助;自己做了下总结

自己弄了一些集合转化的文章;

对于技术方面的理论我不需多言;

主要是是通过映射命名空间;使用Linq的相关查询;和Type类获取列名;使用泛型转化为实体类后放到集合:

代码如下:

 1 publicstaticclass ConvertTolistInfo 2     { 3 ///<summary> 4 /// DataTable 转换为List 集合    5 ///</summary> 6 ///<typeparam name="T">类型</typeparam> 7 ///<param name="dt">DataTable</param> 8 ///<returns></returns> 9 publicstatic List<TResult> ToList<TResult>(this DataTable dt) where TResult : class,new()10         {11             List<PropertyInfo> prlist =new List<PropertyInfo>();12             Type t =typeof(TResult);13             Array.ForEach<PropertyInfo>(t.GetProperties(), p => { if (dt.Columns.IndexOf(p.Name) !=-1)prlist.Add(p); });14             List<TResult> objlist =new List<TResult>();15 foreach (DataRow row in dt.Rows)16             {17                 TResult obj =new TResult();18                 prlist.ForEach(p =>19                 {20 if (row[p.Name] != DBNull.Value)21                         p.SetValue(obj, row[p.Name], null);22                 });23                 objlist.Add(obj);24             }25 return objlist;26         }27 ///<summary>28 /// 转换为一个DataTable  29 ///</summary>30 ///<typeparam name="T"></typeparam>31 ///<param name="value"></param>32 ///<returns></returns>33 publicstatic DataTable ToDataTable<T>(this IEnumerable<T> value) where T : class34         {35             List<PropertyInfo> plist =new List<PropertyInfo>();36             Type t =typeof(T);37 //T type = new T();38 //Type columen = type.GetType();这种方式与 where T :new()这种方式使用 否则不适用;39             DataTable dt =new DataTable();40             Array.ForEach<PropertyInfo>(t.GetProperties(), p =>41             {42                 plist.Add(p);43                 dt.Columns.Add(p.Name, p.PropertyType);44             });45 foreach (var item in value)46             {47 //创建一个DataRow实例  48                 DataRow row = dt.NewRow();49 //给row 赋值 50                 plist.ForEach(p => row[p.Name] = p.GetValue(item, null));51                 dt.Rows.Add(row);52             }53 return dt;54         }55     }

  二,构造泛型类:

/// <summary>/// 实体转换辅助类/// </summary>publicclass ModelConvertHelper<T>where T : new()    {publicstatic IList<T> ConvertToModel(DataTable dt)        {// 定义集合            IList<T> ts =new List<T>();

// 获得此模型的类型            Type type =typeof(T);

string tempName ="";

foreach (DataRow dr in dt.Rows)            {                T t =new T();

// 获得此模型的公共属性                PropertyInfo[] propertys = t.GetType().GetProperties();

foreach (PropertyInfo pi in propertys)                {                    tempName = pi.Name;

// 检查DataTable是否包含此列if (dt.Columns.Contains(tempName))                    {// 判断此属性是否有Setterif (!pi.CanWrite) continue;

object value = dr[tempName];if (value != DBNull.Value)                            pi.SetValue(t, value, null);                    }                }

ts.Add(t);            }return ts;        }

/// <summary>          /// 提供将DataTable类型对象转换为List集合          /// </summary>          /// <param name="table"></param>          /// <returns></returns>  publicstatic List<T> ConvertToList<T>(DataTable table) where T : new()        {//置为垃圾对象             List<T> list =null;if (table !=null)            {                DataColumnCollection columns = table.Columns;int columnCount = columns.Count;                T type =new T();                Type columnType = type.GetType();                PropertyInfo[] properties = columnType.GetProperties();if (properties.Length == columnCount)                {                    list =new List<T>();foreach (DataRow currentRow in table.Rows)                    {for (int i =0; i < columnCount; i++)                        {for (int j =0; j < properties.Length; j++)                            {if (columns[i].ColumnName == properties[j].Name)                                { properties[j].SetValue(type, currentRow[i], null); }                            }                        }                        list.Add(type); type =new T();                    }                }else { list =null; }            }else            {thrownew ArgumentNullException("参数不能为空");            }return list;        }

}

  

时间: 2024-08-02 15:42:17

关于DataTable与IList和List泛型集合的相互转换在网上总结的相关文章

DataTable填充实体类返回泛型集合

     昨天找坤哥看到我的一段代码,如下:           稍微解释下,这段代码时D层查询结束后,将datatable查询到的结果赋值给实体对象的属性,然后返回实体的过程,坤哥看了之后问我,如果实体有500多个属性,难道也要这样一条一条的写吗?如果返回多个实体时怎么办?这时,我才意识到自己的代码时非常有问题的,原来设计的是每个方法最多返回一个实体,但是当遇到查询到多条记录的时候,就又冒着破坏三层结构的事返回Datatable去了,真的是很有问题啊.      怎么改,我脑海中一下子就浮现了

[工具类]DataTable与泛型集合List互转

写在前面 工作中经常遇到datatable与list,对于datatable而言操作起来不太方便.所以有的时候还是非常希望通过泛型集合来进行操作的.所以这里就封装了一个扩展类.也方便使用. 类 方法中主要使用了反射的方式动态的为属性赋值以及取值. public static class Extension { /// <summary> /// 将datatable转换为泛型集合 /// </summary> /// <typeparam name="TEntity

[工具类]泛型集合转换为DataTable

写在前面 在实际项目中,用到了将集合转换为DataTable,就试着封装了一个方法,记录一下. 代码 using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; namespace Wolfy.List2DataTable { class

关于datatable转化为对象数组或泛型集合的性能问题

问题描述 1.如果用datatable返回数据,绑定到页面用eval("字段"),相当的麻烦,得写每一字段:(不会自动感应)2.如果用sqldatareader取出数据装入一个对象数组,页面就就可以用对象[索引].属性来访问数据,貌似很灵活,但问题是就不能使用datatable封装的方法来进行计算,得手工写N多SQL:3.如果用datatable回传数据,然后把datatable转化为对象数组或泛型集合,然后页面中就可以使用 对象[索引].属性来访问数据,并且也可以正常使用datata

泛型集合序列化成jsonp格式返回

问题描述 先有一个IList<Entity.CyberEntity>result=newList<Entity.CyberEntity>();这样的result的泛型集合,我想把resule序列化成jsonp的返回格式.求高手指点.. 解决方案 解决方案二:///<summary>///将datatable转换为json///</summary>///<paramname="dtb">Dt</param>///&l

通过反射填充泛型集合List的静态方法

集合|静态 呃```花了一晚上时间,终于搞出来了如何通过反射,从DataReader将数据填充到数据实体泛型集合的静态方法. //Kchen.Core.BaseBusinessObject为通用数据实体类,此处仅为限定T所继承的类型        public static IList<T> FillDataListGeneric<T>(System.Data.IDataReader reader) where T : Kchen.Core.BaseBusinessObject  

泛型--集合接口

9.4 集合接口 .NET Framework为集合的枚举和对比提供了两组标准接口:传统的(非类型安全)和新的泛型类型安全集合.本书只聚焦于新的,类型安全的集合接口,因为它更优越. 您可以声明一些指定了类型的ICollection来取代实际类型(如int或string),以用于接口声明中的泛型类型(<T>). C++程序员需要注意:C#泛型和C++中的模板在语法和用法上都很相似.但是,因为泛型在运行期为其指定类型进行扩展,JIT编译器可以为它们的不同的实例共享一段代码,从而使得在使用C++模板

C#中把任意类型的泛型集合转换成SQLXML数据格式的实例_C#教程

话不多说,跟着小编一起来看下吧 using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Data.SqlTypes; using System.Data; using System.Reflection; using System.IO; using System.Xml; namespace CollectionToXml { class Program

编写高质量代码改善C#程序的建议:泛型集合、选择集合和集合的安全

前言 软件开发过程中,不可避免会用到集合,C#中的集合表现为数组和若干集合类.不管是数组还是集合类,它们都有各自的优缺点.如何使用好集合是我们在开发过程中必须掌握的技巧.不要小看这些技巧,一旦在开发中使用了错误的集合或针对集合的方法,应用程序将会背离你的预想而运行. 本文已更新至http://www.cnblogs.com/aehyok/p/3624579.html .本文主要学习记录以下内容: 建议20.使用泛型集合来替代非泛型集合 建议21.选择正确的集合 建议22.确保集合的线性安全 建议