Transform any tree into another one

Sometimes I need to convert a domain object that represents a tree into another form of tree, whether to send it over the cable or simply for display it in a user control.

Here the code:

public static IEnumerable<TResult> TransformTree<TSource, TResult>(
         this IEnumerable<TSource> enumerable,
         Func<TSource, IEnumerable, TResult>  transformFunction,
         Func<TSource, IEnumerable<TSource>> getChildrenFunction)
{
 foreach (var item in enumerable)
 {
     yield return transformFunction.Invoke(item,
         getChildrenFunction.Invoke(item)
                            .TransformTree(transformFunction, getChildrenFunction)
         );
 }
}
This is an extension method for IEnumerable<TSource> (almost any collection type) that returns an IEnumerable<TResult>. The second parameter is the “transform function”, in this place you must specify how transform TSource in TResult. The third parameter is the “get children function”, here you must specify how to retrieve the children from TSource. I use this function to build a graph object to put into extjs tree panel as json. Take a look at the code:
var query = daoPersons.ToList().Where( x => x.Father == null)
                          .TransformTree((person, childrenColl) => new
                          {
                              id = person.Id.ToString(),
                              text = person.Name + " " + person.LastName,
                              cls = "folder",
                              leaf = (person.HasChildren()),
                              children = childrenColl
                          }, person => person.Children);

return Json(query);
I hope you like it!

PS: I think you should avoid the anonymous type for testing purpose.


blog comments powered by Disqus
  • Categories

  • Archives