Tuesday, May 31, 2011

Iterate down a tree

Very often I see code like:

var list = new List<foo>();
AddRecursive(list, foo);
return list;

Nothing wrong with that except that there will be a lot of duplicate code after a while.

After some testing I was able to create an enumerator walking the tree.

public static IEnumerable<T> Recursive<T>(
T node, Func<T, IEnumerable<T>> selector)
yield return node;
var children = selector(node);
if (children == null) yield break;

foreach (var child in children.SelectMany(x => Recursive(x, selector)))
yield return child;

Let say you have this class:

public class Node {
public int Id;
public Node[] Children;

You can now find a given node using this statement

var node = Recursive(root, x => x.Children)
.FirstOrDefault(x => x.Id == 10);

No comments:

Post a Comment