The significance of this paper is not only to illustrate how to convert IList into a DataTable, but to give an idea of how to use reflection to realize the transformation of various data structures (collection classes) into a common method.
I believe many friends who have used NHibernate know that access to the database via NH, data are returned in IList form, this is for us in. The use of traditional data binding in net is inconvenient. Since the objects loaded by the IList returned by NH are often different, we will write the conversion method separately for each returned list, and the reflection mechanism can be used to make a common conversion method.
usingSystem;usingSystem.Collections.Generic;usingSystem.Text;usingSystem.Data;usingSystem.Collections;usingSystem.Reflection;namespacekycbasemodule{ Public classkycfunction { Publickycfunction () {}/**//// <summary> ///Implementing a conversion to an IList-to-dataset/// </summary> /// <param name= "Reslist" >IList to convert</param> /// <returns>the converted dataset</returns> Public StaticDataSet Listtodataset (IList reslist) {DataSet RDS=NewDataSet (); DataTable TEMPDT=NewDataTable (); //This iterates over the structure of the IList and establishes the same DataTableSystem.reflection.propertyinfo[] p = reslist[0]. GetType (). GetProperties (); foreach(System.Reflection.PropertyInfo Piinchp) {TempDT.Columns.Add (pi). Name,system.type.gettype (pi. Propertytype.tostring ())); } for(inti =0; i < Reslist.count; i++) {IList templist=NewArrayList (); //writes a record in the IList to ArrayList foreach(System.Reflection.PropertyInfo Piinchp) {Objectoo = pi. GetValue (Reslist[i],NULL); Templist.add (OO); } Object[] itm=New Object[P.length]; //traverse ArrayList to object[] to place data for(intj =0; J < Templist.count; J + +) {itm. SetValue (Templist[j], J); } //put the contents of object[] into a DataTableTempdt.loaddatarow (ITM,true); } //put datetable into a datasetRDS. Tables.add (TEMPDT); //return DataSet returnRDS; } }}
As you can see from the code above, the implementation process is very simple. First, using reflection, the attributes contained in the IList of the incoming method are fetched, then the columns of the DataTable is established based on the obtained properties, and then the entire IList is iterated through the loop, and the contents of each node object are copied sequentially to the DataTable. Since the code is taken from the real Project module, the original namespace is preserved and several rows of the DataTable are placed in the dataset.
Source: http://www.soaspx.com/dotnet/asp.net/tech/tech_20110124_7144.html
Ilist<t> Turn DataTable