Iterate through child to parent

I’m claming data from following query,

    var targetItems = await _dbContext.TargetItems
        .Include(ti => ti.BranchTargetItem)
        .ThenInclude(bti => bti.BranchTarget)
        .ToListAsync(cancellationToken);

I need to find a way to sum values from bottom to top level in my tree. Must sum values respectively regarding its own first level child values like I commented out below,
targetItems = {
   "item":"A",
   "values":14, << sum of B + C values
   "childs":[
      {
         "item":"B",
         "values":2,
         "childs":[]
      },
      {
         "item":"C", << sum of D + E + H values
         "values":12,
         "childs":[
            {
               "item":"D",
               "values":5,
               "childs":[]
            },
            {
               "item":"E",
               "values":4, << sum of F + G values
               "childs":[
                  {
                     "item":"F",
                     "values":2,
                     "childs":[]
                  },
                  {
                     "item":"G",
                     "values":2,
                     "childs":[]
                  }
               ]
            },
            {
               "item":"H",
               "values":3,
               "childs":[]
            }
         ]
      }
   ]
}

Not able to post any code here because, I am not even close to solution.

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

int SetSumOfChildren(object node){
  if(!(node.childs?.Any() ?? false)){
    node.values = node.values ?? 0;
  }
  else {      
    int sum = 0;
    foreach(var n in node.childs){
      sum += SetSumOfChildren(n);
    }
    node.values = sum;
  }
  return node.values;
}

SetSumOfChildren(data);


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x