(ID/ParentID) list to Hierarchical list

后端 未结 3 942
清酒与你
清酒与你 2020-12-05 05:47

MyClass consists of ID ParentID and List as Children

I have list of MyClass

3条回答
  •  -上瘾入骨i
    2020-12-05 06:25

    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 };
        }
    

提交回复
热议问题