Skip to content

Instantly share code, notes, and snippets.

@mpfund
Created August 20, 2013 23:35
Show Gist options
  • Save mpfund/6288711 to your computer and use it in GitHub Desktop.
Save mpfund/6288711 to your computer and use it in GitHub Desktop.
Walk Trees
public static class WalkTreeExtension
{
public static void DoWalk<T>(this IEnumerable<T> ienu, Action<T> a, Func<T,IEnumerable<T>> childs)
{
foreach(var e in ienu)
{
a(e);
DoWalk(childs(e), a, childs);
}
}
public static IEnumerable<Y> TransformTree<T,Y>(this IEnumerable<T> elements, Func<T,Y> transformAction, Func<T, IEnumerable<T>> childsFromElement, Action<Y,Y> addChildToTarget)
{
var newTree = new List<Y>();
foreach (var e in elements)
{
var newElement = transformAction(e);
newTree.Add(newElement);
foreach (var el in TransformTree(childsFromElement(e), transformAction, childsFromElement,addChildToTarget))
{
addChildToTarget(newElement,el);
}
}
return newTree;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment