Sometimes we retrieve data in flat model from database. But we need data in hierarchical form in some cases. At that moment the following example may useful which explains how to convert flat data to hierarchical data. The below example uses csharp and linq to convert flat to hierarchical
For instance, take a flat object as shown below
List<FlatObject> flatObjects = new List<FlatObject> { new FlatObject("Category",1,0), new FlatObject("Sub Category 1",2,1), new FlatObject("Sub Category 2",3,1), new FlatObject("Item 1",4,2), new FlatObject("Item 2",5,2), new FlatObject("Item 3",6,2), new FlatObject("Item 4",7,3), new FlatObject("Item 5",8,3), new FlatObject("Item 6",9,3) };
The class used to create above flat object is
public class FlatObject { public int Id { get; set; } public int ParentId { get; set; } public string Data { get; set; } public FlatObject(string name,int id, int parentId) { Data = name; Id = id; ParentId = parentId; } }
Now create a recursive class as shown below
public class RecursiveObject { public int Id { get; set; } public int ParentId { get; set; } public string Data { get; set; } public List<RecursiveObject> Children { get; set; } }
The below method used with linq returns the above flat data as hierarchical data
private static List<RecursiveObject> FillRecursive(List<FlatObject> flatObjects, int parentId) { List<RecursiveObject> recursiveObjects = new List<RecursiveObject>(); foreach (var item in flatObjects.Where(x => x.ParentId.Equals(parentId))) { recursiveObjects.Add(new RecursiveObject { Data = item.Data, Id = item.Id, Children = FillRecursive(flatObjects, item.Id) }); } return recursiveObjects; }
Call the above methos as shown which retuns the required object
var recursiveObjects = FillRecursive(flatObjects, 0);
The hierarchical data is used to bind to the controls which require them. An example to bind hierarchical data to jstree (a jquery plugin used to create a treeview) in MVC 3 razor is explained in next article.
Comments/Suggestions are invited. Happy coding......!
Comments Post a Comment
Gopala Rao 1/29/2013 (IST) / Reply
How to create stored procedure for treeview for a table having parent,child,subchild
Navneet 4/21/2013 (IST) / Reply
pls give the good example of state managment. techniques with real world example..like one u given in threading with bank transaction and updation in database simultaneously.
Arvind upadhyay 6/20/2016 (IST) / Reply
helpful