This one cropped up at work recently. As part of a project there was a requirement for an API to carry out a check as part of an update on an object to ensure that none of the object’s children met a certain criteria (I’m avoiding business context here).
I thought I’d sail through this and it would be a breeze but before I knew it I was getting tangled up in loops and in a right old mess. Whilst it’s very easy to get the direct children it’s more difficult to get their children (and so on). I needed a nice simple succinct approach with a sprinkling of code. Also, there appears to be little online that goes beyond simply getting the immediate children or writing lines of code or building up loads of extension methods.
So, removing the business context. Here’s a solution
There is a final consideration here. If you specify the “God” Id (1) then you’ll receive a stack overflow message. So a there’s room for improvement (comments below please). In the meantime I’ll use a belt and braces approach to handle an Id of 1.