In the project, encountered the use of converting a collection to a DataTable, read the information on the Internet, recorded here, and shared.
usingSystem;usingSystem.Collections.Generic;usingSystem.Data;usingSystem.Linq;usingSystem.Reflection;usingSystem.Text;usingSystem.Threading.Tasks;namespacewolfy.list2datatable{classProgram {Static voidMain (string[] args) {List<Person> LST =NewList<person>() { NewPerson () {id=1, gender=false, name="wolfy1"}, NewPerson () {id=2, gender=false, name="wolfy2"}, NewPerson () {id=3, gender=false, name="Wolfy3"}, NewPerson () {id=4, gender=false, name="Wolfy4"}, NewPerson () {id=5, gender=false, name="wolfy5"}, }; DataTable DT= list2datatable<person>(LST); Console.WriteLine ("End of conversion"); Console.read (); } /// <summary> ///convert a generic collection to a DataTable/// </summary> /// <typeparam name= "TEntity" ></typeparam> /// <param name= "entities" ></param> /// <returns></returns> StaticDataTable list2datatable<tentity> (list<tentity>entities) { if(Entities = =NULL) { Throw NewArgumentNullException ("The collection of conversions is empty"); } Type Type=typeof(TEntity); Propertyinfo[] Properties=type. GetProperties (); DataTable DT=NewDataTable (type. Name); foreach(varIteminchproperties) {dt. Columns.Add (NewDataColumn (item. Name) {DataType =item. PropertyType}); } foreach(varIteminchentities) {DataRow row=dt. NewRow (); foreach(varPropertyinchproperties) {Row[property. Name]=Property . GetValue (item); } dt. Rows.Add (row); } returnDT; } } Public classPerson { Public intID {Set;Get; } Public stringName {Set;Get; } Public BOOLGender {Set;Get; } }}
Generic collection converted to DataTable