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.
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);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.