Problem description: |
When retrieving the database record data, the arraylist set is usually returned without a hierarchy. if you re-obtain records from the database based on the PID each time, you can do so, but there are the following Disadvantages: 1. the number of database access records increases as the number of records increases. 2. because the database needs to be accessed multiple times, the access speed is affected. it requires support from the database access layer and records are converted. The coupling is too strong. 4. poor versatility. Each time a new type list is required |
|
Solution: |
Based on the original tree structure Algorithm Code Write a general algorithm that uses the reflection principle to recursively filter data. in this way, you only need to access the database once, and then traverse it in the memory, and it is suitable for sorting all entity classes with (PID, ID, name) attributes. if you need to generate a tree structure of a collection of object classes of the device type, the Code is as follows: Arraylist equiptypelist = EquipmentType. getall (); Equiptypelist = Collectionhelper. gettreeitems (equiptypelist ); This . Ddlequipmenttypes. datasource = Equiptypelist; This . Ddlequipmenttypes. datatextfield = " Name " ; This . Ddlequipmenttypes. datavaluefield = " ID " ; This . Ddlequipmenttypes. databind ();
This . Ddlequipmenttype. Items. insert ( 0 , New Listitem ( " (All) " , " 0 " )); |
|
Public Class Collectionhelper
{
Private Static Arraylist fill ( Int PID, Int Level, arraylist List)
{
Arraylist returnlist = New Arraylist ();
Foreach ( Object OBJ In List)
{
Int Typepid = ( Int ) Reflectionutil. getproperty (OBJ, " PID " );
Int Typeid = ( Int ) Reflectionutil. getproperty (OBJ, " ID " );
String Typename = Reflectionutil. getproperty (OBJ, " Name " ) As String ;
If (PID = Typepid)
{
String Newname = New String ( ' - ' , Level * 4 ) + Typename;
Reflectionutil. setproperty (OBJ, " Name " , Newname );
Returnlist. Add (OBJ );
Returnlist. addrange (fill (typeid, Level + 1 , List ));
}
}
Return Returnlist;
}
/**/ /// <Summary>
/// Generate a list with hierarchies
/// </Summary>
/// <Param name = "list"> Any set with name, ID, and PID members </Param>
/// <Returns> </returns>
Public Static Arraylist gettreeitems (arraylist List)
{
ReturnFill (-1,0, List );
}
}
Public Sealed Class Reflectionutil
{
Private Reflectionutil ()
{}
Public Static Bindingflags BF = Bindingflags. declaredonly | Bindingflags. Public |
Bindingflags. nonpublic | Bindingflags. Instance | Bindingflags. Static;
Public Static Void Setproperty ( Object OBJ, String Name, Object Value)
{
Propertyinfo fi=OBJ. GetType (). getproperty (name, BF );
Fi. setvalue (OBJ, value,Null);
}
Public Static Object Getproperty ( Object OBJ, String Name)
{
Propertyinfo fi=OBJ. GetType (). getproperty (name, BF );
ReturnFi. getvalue (OBJ,Null);
}
}
As follows: