Nothing to do, only write code, the following is the DataTable to list and list to the two methods of the DataTable, the main technical points to use the principle of reflection:
/// <summary> ///Model Transformation Classes/// </summary> Public classConvertmodel {/// <summary> ///DataTable Goto List/// </summary> /// <typeparam name= "T" >types in list</typeparam> /// <param name= "DT" >the DataTable to convert</param> /// <returns></returns> Public StaticList<t> datattabletolist<t> (DataTable DT)whereT:class,New() {List<T> list =NewList<t>(); T T=NewT (); Propertyinfo[] Prop=T.gettype (). GetProperties (); //traverse all rows of a DataTable foreach(DataRow Drinchdt. Rows) {T=NewT (); //get all members of type T by Reflection foreach(PropertyInfo Piinchprop) { //DataTable Column Name = property name if(dt. Columns.contains (pi. Name)) {//property value is not empty if(Dr[pi. Name]! =dbnull.value) {ObjectValue =Convert.changetype (Dr[pi. Name], pi. PropertyType); //Assigning a value to a field of type TPi. SetValue (t, value,NULL); } } } //Add the T type to the collection listlist. ADD (t); } returnlist; } /// <summary> ///List converted to DataTable/// </summary> /// <typeparam name= "T" >types in list</typeparam> /// <param name= "List" >the list to convert</param> /// <returns></returns> Public StaticDataTable listtodatatable<t> (list<t> List)whereT:class{DataTable dt=NewDataTable (); Propertyinfo[] Prop=typeof(T). GetProperties (); Datacolumn[] Columnarr= Prop. Select (p =NewDataColumn (P.name, P.propertytype)). ToArray (); Dt. Columns.addrange (Columnarr); foreach(T Tinchlist) {DataRow Dr=dt. NewRow (); foreach(PropertyInfo Piinchprop) { if(dt. Columns.contains (pi. Name)) {if(pi.) GetValue (t)! =NULL) {Dr[pi. Name]=Pi. GetValue (t); }}} dt. Rows.Add (DR); } returnDT; } }
Call:
DataTable dt =NewDataTable (); Dt. Columns.Add ("Id"); Dt. Columns.Add ("Sex"); Dt. Columns.Add (" Age"); Dt. Columns.Add ("Height"); DataRow Dr=dt. NewRow (); dr["Id"] =1; dr["Sex"] =1; dr[" Age"] = -; dr["Height"] = the; Dt. Rows.Add (DR); //Convert a DataTable to list<persion>List<persion> List1 = convertmodel.datattabletolist<persion>(DT); List<Persion> list =NewList<persion>() { NewPersion () {id=1, sex=1, age= -, height=168}, NewPersion () {id=2, sex=0, age= -, height=168}, }; //convert list<persion> to DataTableDataTable dt1 = convertmodel.listtodatatable<persion> (list);
C # DataTable to List and list to DataTable