Thanks to nHibernate, some of the data structures I work with are lists within lists within lists. So for example I have a data object called “category” which has a .Children property that resolves to a list of categories … each one of which can have children … and so on and so on.
I need to find a way of starting at a top-level category in this structure and getting a list or array or something similar of all the children in the entire structure – so all the children of all the children etc etc, flattened into a single list.
I’m sure it can be done with recursion, but I find recursive code a pain to work through, and I’m convinced there must be a more straightforward way in .Net 4 using Linq or somesuch – any suggestions?
Assuming your Category class looks something like:
I don’t think there’s an “easy” non-recursive way to do it; if you’re simply looking for a single method call to handle it, the “easy” way is to write the recursive version into a single method call. There’s probably an iterative way to do this, but I’m guessing it’s actually pretty complicated. It’s like asking the “easy” way to find a tangent to a curve without using calculus.
Anyway, this would probably do it: