In a recent case, you need to bind an array of entities, such as materiel [], to the interface (winform/webform). Although Arrays can be directly bound to the gridview, sorting and filtering are required, search and other operations are not very convenient in the array. So I want to use datatable as the data source.
The simplest way is to manually create a able. Create a column for each materiel property and specify its data type. After creating a table, create a new row for each materiel cyclically. If there are several interfaces, although they are almost doneCodeIt is difficult to reuse.
In addition, the data is obtained from the WebService, and the form does not allow direct access to the DB, so the adoable cannot be obtained through ado.net.
After a period of consideration, we decided to see a dedicated utility class entitycollectionsconvert. The interface is
Datatable todatatable (object [] entitys );
Datatable todatatable<T>(List<T>Entitys)
The implementation principle is also relatively simple
1. entitys is not null;
2. Retrieve all properties of entitys
3. Add a column (including element type) for each property in datatable)
4. Add a row for each entity.
5. automatically generate a unit test, test, and add it to the project.
1 public static datatable todatatable <t> (list <t> entitys) <br/> 2 {<br/> 3 <br/> 4 // check that the object set cannot be empty <br/> 5 If (entitys = NULL | entitys. count <1) <br/> 6 {<br/> 7 throw new exception ("the set to be converted is empty "); <br/> 8} <br/> 9 <br/> 10 // retrieve all properties of the first object <br/> 11 type entitytype = entitys [0]. getType (); <br/> 12 propertyinfo [] entityproperties = entitytype. getproperties (); <br/> 13 <br/> 14 // generate the structure of the datatable <br /> 15 // In the production code, the generated able structure should be cached, here slightly <br/> 16 datatable dt = new datatable (); <br/> 17 for (INT I = 0; I <entityproperties. length; I ++) <br/> 18 {<br/> 19 DT. columns. add (entityproperties [I]. name, entityproperties [I]. propertytype); <br/> 20} <br/> 21 <br/> 22 // Add all entity to datatable <br/> 23 foreach (Object entity in entitys) <br/> 24 {<br/> 25 // check that all entities belong to the same type <br/> 26 if (entity. getType ()! = Entitytype) <br/> 27 {<br/> 28 throw new exception ("the element types of the set to be converted are inconsistent "); <br/> 29} <br/> 30 object [] entityvalues = new object [entityproperties. length]; <br/> 31 for (INT I = 0; I <entityproperties. length; I ++) <br/> 32 {<br/> 33 entityvalues [I] = entityproperties [I]. getvalue (entity, null); <br/> 34 <br/> 35} <br/> 36 DT. rows. add (entityvalues); <br/> 37} <br/> 38 return DT; <br/> 39} <br/>