[英]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.无法在此处发布任何代码,因为我什至还没有接近解决方案。
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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.