MyClass
consists of ID
ParentID
and List
as Children
I have list of MyClass
I have required such functionality and compare both methods and find method 2nd is faster than 1st :), right now in my database cards or records are limited but 1st method taking 4 times more time to complete.
may be this can help for those who are conscious about time.
1 method
public JsonResult CardData()
{
var watch = System.Diagnostics.Stopwatch.StartNew();
OrgChartWithApiContext db = new OrgChartWithApiContext();
var items = db.Cards.ToList();
Action SetChildren = null;
SetChildren = parent => {
parent.Children = items
.Where(childItem => childItem.ParentId == parent.id)
.ToList();
//Recursively call the SetChildren method for each child.
parent.Children
.ForEach(SetChildren);
};
//Initialize the hierarchical list to root level items
List hierarchicalItems = items
.Where(rootItem => !rootItem.ParentId.HasValue)
.ToList();
//Call the SetChildren method to set the children on each root level item.
hierarchicalItems.ForEach(SetChildren);
watch.Stop();
var timetaken = watch.ElapsedMilliseconds;
return new JsonResult() { Data = hierarchicalItems, ContentType = "Json", JsonRequestBehavior = JsonRequestBehavior.AllowGet };
}
method 2
public JsonResult Card2Data()
{
var watch = System.Diagnostics.Stopwatch.StartNew();
OrgChartWithApiContext db = new OrgChartWithApiContext();
var items = db.Cards.ToList();
List topItems = items.Where(item => !item.ParentId.HasValue).ToList();
topItems.ForEach(item => item.Children = items.Where(child => child.ParentId == item.id).ToList());
watch.Stop();
var timetaken = watch.ElapsedMilliseconds;
return new JsonResult() { Data = topItems, ContentType = "Json", JsonRequestBehavior = JsonRequestBehavior.AllowGet };
}