How to filter for a specific object in a nested list and get the resulting object with parent items
I have a list of nested objects that looks like this:
I know that I could find a specific nested object by value (ie get an
Item
with Title="some string") if I loop through the list and its nested items. I've written a recursive method extension that does this. But with such a method, I only get the specific child item:
Is there a way I can also get the parent items as shown below? :ThonkAnime: Maybe I'm just missing out on some funky foreach algorithm or there's a linq method out there that does this already
Trying to search this in google, the results just say to flatten the list with SelectMany, but that only works for a single level of nesting :xdd: Not even god knows which level of nesting I can expect to find my item at, so chaining selectmany's here is not possible.6 Replies
As you recurse, you can keep a stack of which parents you've recursed through
Give me a min to throw together an example...
Ah yes, this approach is what I'm looking for, though I'm worried how references are kept throughout each recursion loop :ThonkAnime: And mostly how to flag the parent objects that matched the child item :FeelsChromosomeMan:
o7 this is massive help in the right direction, thanks
normally you would have a dfs:
then you will notice that there is an local variable
i
in the dfs
, that means in your stack you capture the i
so
btw a much simpler way is to have an additional stack in dfs, push the parent when you enter and pop it before you leave