This is a follow up post to this one: Recursively search nested lists
I’ve been attempting to modify the code that resulted to allow me to return a parent item of whatever child is located, but the recursive aspect of this function doesn’t flow in my brain very well for some reason.
In a perfect world I’d like to be able to specify how many parent nodes up to return, but even just the immediate would be great.
public static AccessibleTreeItem Find(AccessibleTreeItem node, string name)
{
if (node == null)
return null;
if (node.name == name)
return node;
foreach (var child in node.children)
{
var found = Find(child, name);
if (found != null)
return found;
}
return null;
}
Thanks all for taking the time to have a look.
Edit: So, for example, I’d like to be able to call Find(node, name, parentIndex) or something similar, to pass through a value that represents the number of parent levels the item being returned can be found at.
Edit 2: To clarify, I would like to be able to tell the function to find a particular name, and a parentIndex. The function would locate the node being searched for, and then traverse up the ‘tree’ the specified number of levels, and finally returning that object.
So if we called
Find(node, "Test", 2)
And the value being searched for was at:
node.children[0].children[3].children[2].children[1]
Then the function should return the object located at:
node.children[0].children[3]
Aha… so try passing down byref a (positive) integer called “ancestorCount” (1 for parent, 2 for grandparent, 3 for great-gran-dad, etc, etc)… if found returns true (not null) and the ancestorCount==0 return this, othewise decrement the ancestorCount before returning the found child…
Does that make sense to you? I’ll edit this post in about 10 minutes to put that into psuedocode (at least).
Cheers. Keith.
EDIT: To provide sort-of code at-least.
This isn’t compiled, let-alone tested… and therefore I’m not at all certain that I’ve got the condition correct… As Ben pointed out, I might have it completely assbackwards 😉 This is kind of thing that I typically have to debug for a while to get right… but I do think “I’m pretty close”, and the core idea is there… I’ll leave the fine-tuning upto the implementor… you 😉
… But I can see that I’m going to have to implement Node now, just to satisfy my own curiosity about the correctness of my algorith. Sigh.
Cheers. Keith.
EDIT2:
Well, this works for me…
OUTPUT
… though in the real world you’d probably “just” implement it with a parent reference in each node, simply because that’s simpler… and useful for other things.