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.
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);
}
}