C# Recursive Hierarchy. Get the parent’s children, and their children, and their children, and ……….

The Issue

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

Easy right?

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.

Ohhh, won’t somebody please think of the children!

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.

Leave a Reply

%d bloggers like this: