Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

114
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda