w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
Is there an easy way to count the elements in a recursive data structure?

A natural way of processing recursive data structures, for count or any other kind of aggregation, is employing a recursive function:

class Part {
    IEnumerable<Part> SubParts {get;set;}
    public int TotalParts {
        get {
            return 1 + SubParts.Sum(p => p.TotalParts);
            //     ^                       ^
            //     |                       |
            // Add one for this part       |
            //                             |
            //         Use LINQ to aggregate counts recursively
        }
    }
}

The function assumes that parts of lower levels are not shared among parts at the higher level, i.e. that your graph of parts is a tree. One way to improve the performance of functions like this is to cache the results at the levels below yours in the Part, to make sure that the recursive computation is done only once.

You could avoid recursion by implementing a queue or a stack, but the implementation wouldn't be that simple.





© Copyright 2018 w3hello.com Publishing Limited. All rights reserved.