Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

113
Views
Summing the child values of a self referencing parent/child list and setting the parents to the sum

I have a list of product entities that are self referencing and can go infinite levels. For example:

Name: Product 1
Parent: null
Value: null

Name: Product 2
Parent: "Product 1"
Value: 20

Name: Product 3
Parent: "Product 2"
Value: null

Name: Product 4
Parent: "Product 3"
Value: 40

Name: Product 5
Parent: "Product 4"
Value: 50

Name: Product 6
Parent: null
Value: null

Name: Product 7
Parent "Product 6"
Value: 30

I am attempting to set any entity that has a null value with the sum of all of the entities below that entity if any of the have values. In the example above I would end up with:

Name: Product 1
Parent: null
Value: 110

Name: Product 2
Parent: "Product 1"
Value: 20

Name: Product 3
Parent: "Product 2"
Value: 90

Name: Product 4
Parent: "Product 3"
Value: 40

Name: Product 5
Parent: "Product 4"
Value: 50

Name: Product 6
Parent: null
Value: 30

Name: Product 7
Parent "Product 6"
Value: 30

I have tried to do a bit of preprocessing, storing the entities in a hashmap but have not been successful.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Transform this flat hierarchy into a true hierarchy and recurse.

public class Node {
  public string Name {get; set;}
  public int Value {get; set;}
  public List<Node> Children = new List<Children>();
}

public int Sum(Node node) {
  int sum = 0;

  foreach(var childnode in node.Children) {
    sum+= Sum(childnode);
  }
  sum+= node.Value
  return sum;
}

//store all nodes
var Nodes = new List<Node>();
foreach(var node in Nodes) {
  if (node.Value = 0) {
   node.Value = Sum(node);
  }
}
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!