Generic Tree Implementation in C#.NET

Recently, I was working on a class which was represented as a hierarchical tree. I wrote several recursive extension methods to operate on this class, after which I realized that these methods could be extracted out into a more generic implementation. I chose to use an interface as opposed to a base class, since my requirements for this application are currently fairly simple: each object will have a property which is an array of the same type.

    public interface ITree
    {
        T[] Children { get; set; }
    }

This implementation does not have a lot of the features of some others that exist on the web, which do use base classes such as Dan Vanderboom’s Tree: Implementing a Non-Binary Tree in C#. In my case, YAGNI!

Here is my current collection of extension methods for this interface. If you have another implementation or other methods I’d love to see them in the comments.

    public static class TreeExtensions
    {
        public static IEnumerable Filter(this IEnumerable items, Func func) where T : ITree
        {
            var results = new List();
            foreach (var item in items)
            {
                item.Children = item.Children.Filter(func).ToArray();
                if (item.Children.Any() || func(item))
                    results.Add(item);
            }
            return results;
        }

        public static IEnumerable Flatten(this IEnumerable items) where T : ITree
        {
            var result = new List();
            foreach (var item in items)
            {
                result.Add(item);
                result.AddRange(item.Children.Flatten());
            }
            return result;
        }

        public static void Apply(this IEnumerable items, Action action) where T : ITree
        {
            foreach (var item in items)
            {
                action(item);
                item.Children.Apply(action);
            }
        }
    }
Posted Thursday, February 9th, 2012 under Uncategorized.

Leave a Reply