Can someone show me how to implement a recursive lambda expression to traverse a tree structure in C#.
Assuming a mythical object TreeItem, that conatins a Children collection to represent your hierarchy.
public void HandleTreeItems(Action item, TreeItem parent)
{
if (parent.Children.Count > 0)
{
foreach (TreeItem ti in parent.Children)
{
HandleTreeItems(item, ti);
}
}
item(parent);
}
Now to call it, passing in the lambda that handles one item, by printing its name to the console.
HandleTreeItems(item => { Console.WriteLine(item.Name); }, TreeItemRoot);