Is it possible to sum hierarchical data using .NET’s LINQ?
My data class looks like this:
class Node
{
public decimal Amount;
public IEnumerable<Node> Children { get; set; }
}
So I would have some data looks like this, but the tree could of course be arbitrarily deep.
var amounts = new Node
{
Amount = 10;
Children = new[]
{
new Node
{
Amount = 20
},
new Node
{
Amount = 30
}
}
};
It is possible sum all the amounts and get the result 60 with one simple LINQ query?
Technically you can write recursive lambda expressions, but you need to be insane or insanely bright to try (I haven’t figured out which). But you can cheat: