Friday, October 17, 2008

Mapping Parents to Children Using Anonymous Types and LINQ

After writing my last post I spent some time thinking about certain places where the DeepEnumerator class helped me, and one of the uses that I came across was based on a particular challenge. I had a class that represented the tree structure that I talked about in my last post, namely it adhered to the following principle:

   1: class T
   2: {
   3:     IEnumerable<T> Children { get; }
   4: }

What I discovered is that it’s fairly common to have a situation where the parent defines it’s children in the aforementioned manner, but often in such cases, the children do not define their parents. What I wanted to do is to handle this case by creating a new class that holds the parent and the child and do it in a generic way.

For the purpose of illustrating anonymous types let’s do it first with anonymous types. Note: The following example uses LINQ for terseness and expressiveness, but it’s not required.

First, given the aforementioned class T, let’s define the anonymous type, given an instance of T called parent.

   1: // assume parent which is the top most
   2: // element in the tree is defined
   3: T parent = new T();
   4: var root = new {Parent=default(T), Element = parent};

This code may look odd but all we really are doing here is defining the concept of a root, and a root is an item that has no parent. We use default(T) to define the type. To enumerate, we know we want to enumerate starting with root, which internally represents a tuple of a parent and child, but the challenge is mapping root to IEnumerable<AnonymousType> where anonymous type is the type of root that we just defined.

To do so let’s use linq:

   1: elementAndParent =>
   2:     {
   3:         var query =
   4:             from child in elementAndParent.Element.Children
   5:             select new { Parent = elementAndParent.Element, Element = child };
   6:  
   7:         return query;
   8:     }

All this does is it takes the elementAndParent and maps it to a query that takes all the children under elementAndParent.Element(which is really the element that we are using currently on the tree) and returns a new anonymous type with that child as Element, and the current element as Parent.

Let’s look at it in the full context. Note I’ve defined our cute dog Kadi here as a person. Call it artistic license:

   1: public class Person
   2: {
   3:     private List<Person> _Children = new List<Person>();
   4:  
   5:     public int Age { get; set; }
   6:     public string FirstName { get; set; }
   7:     public string LastName { get; set; }
   8:  
   9:     public List<Person> Children
  10:     {
  11:         get { return _Children; }
  12:     }
  13: }
  14: private void TestParents()
  15: {
  16:     Person parent = new Person();
  17:     parent.FirstName = "Bob";
  18:     parent.LastName = "Philpott";
  19:  
  20:     Person child1 = new Person();
  21:     child1.FirstName = "Brooke";
  22:     child1.LastName = "Philpott";
  23:  
  24:     Person child2 = new Person();
  25:     child2.FirstName = "Stephen";
  26:     child2.LastName = "Philpott";
  27:  
  28:     Person pet1 = new Person();
  29:     pet1.FirstName = "Kadi";
  30:     pet1.LastName = "Philpott";
  31:  
  32:     parent.Children.Add(child1);
  33:     parent.Children.Add(child2);
  34:  
  35:     child1.Children.Add(pet1);
  36:  
  37:     var root = new { Parent = default(Person), Element = parent };
  38:     var allElementAndParents =
  39:             Intercerve.Collections.Generic.DeepEnumerator.Enumerate(
  40:             root,
  41:             elementAndParent =>
  42:             {
  43:                 var query =
  44:                     from child in elementAndParent.Element.Children
  45:                     select new { Parent = elementAndParent.Element, Element = child };
  46:  
  47:                 return query;
  48:             });
  49:  
  50:     foreach (var elementAndParent in allElementAndParents)
  51:     {
  52:         if (elementAndParent.Parent == null)
  53:         {
  54:             continue;
  55:         }
  56:  
  57:         string message = string.Format("{0} is the parent of {1}", elementAndParent.Parent.FirstName, elementAndParent.Element.FirstName);
  58:         System.Diagnostics.Debug.WriteLine(message);
  59:     }
  60: }

Note I filtered out entries that don’t have parents, as those are roots and I don’t really care about them.

The only drawback to this approach is that anonymous types have to be local in scope, which prevents me from reusing this code (obviously not ideal). To fix this let’s declare the anonymous type as a real type:

   1: class ElementAndParent<T>
   2: {
   3:     public T Element { get; set; }
   4:     public T Parent { get; set; }
   5: }

Once we have this helper class we can define a function like so:

   1: private static IEnumerable<ElementAndParent<T>> GetElementsWithParentsDeep<T>(
   2:     T parent, 
   3:     Func<T, IEnumerable<T>> childMappingFunction)
   4: {
   5:     var root = new ElementAndParent<T> { Parent = default(T), Element = parent };
   6:     var allElementAndParents =
   7:             Intercerve.Collections.Generic.DeepEnumerator.Enumerate(
   8:             root,
   9:             elementAndParent =>
  10:             {
  11:                 var query =
  12:                     from child in childMappingFunction(elementAndParent.Element)
  13:                     select new ElementAndParent<T> { Parent = elementAndParent.Element, Element = child };
  14:  
  15:                 return query;
  16:             })
  17:             .Where(item=>item.Parent != null);
  18:  
  19:     return allElementAndParents;
  20: }

What if we wanted to be able to walk all the way up the parents from the current node. Pretty easy actually. We just make a couple modifications. First let us define a class:

   1: private class ElementAndParentExtended<T>
   2:     {
   3:         public T Element { get; set; }
   4:         public ElementAndParentExtended<T> Parent { get; set; }
   5:     }

This class basically makes parent the same type as the type itself, allowing us to get the parent’s parent. We can then modify the enumeration like so:

   1: private static IEnumerable<ElementAndParent<T>> GetElementsWithParentsDeep<T>(
   2:     T parent, 
   3:     Func<T, IEnumerable<T>> childMappingFunction)
   4: {
   5:     var root = new ElementAndParent<T> { Parent = default(T), Element = parent };
   6:     var allElementAndParents =
   7:             Intercerve.Collections.Generic.DeepEnumerator.Enumerate(
   8:             root,
   9:             elementAndParent =>
  10:             {
  11:                 var query =
  12:                     from child in childMappingFunction(elementAndParent.Element)
  13:                     select new ElementAndParent<T> { Parent = elementAndParent.Element, Element = child };
  14:  
  15:                 return query;
  16:             })
  17:             .Where(item=>item.Parent != null);
  18:  
  19:     return allElementAndParents;
  20: }

To test, let’s make a new method:

   1: private static void TestParents2()
   2: {
   3:     Person parent = new Person();
   4:     parent.FirstName = "Bob";
   5:     parent.LastName = "Philpott";
   6:  
   7:     Person child1 = new Person();
   8:     child1.FirstName = "Brooke";
   9:     child1.LastName = "Philpott";
  10:  
  11:     Person child2 = new Person();
  12:     child2.FirstName = "Stephen";
  13:     child2.LastName = "Philpott";
  14:  
  15:     Person pet1 = new Person();
  16:     pet1.FirstName = "Kadi";
  17:     pet1.LastName = "Philpott";
  18:  
  19:     parent.Children.Add(child1);
  20:     parent.Children.Add(child2);
  21:  
  22:     child1.Children.Add(pet1);
  23:  
  24:     var parentsExtended = GetElementsWithParentsExtendedDeep(parent, item => item.Children);
  25:     foreach (var item in parentsExtended)
  26:     {
  27:         if (item.Parent == null)
  28:         {
  29:             continue;
  30:         }
  31:  
  32:         StringBuilder message = new StringBuilder(item.Element.FirstName);
  33:         var itemParent = item.Parent;
  34:         while (itemParent != null)
  35:         {
  36:             message.Append(" is the child of " + itemParent.Element.FirstName);
  37:             itemParent = itemParent.Parent;
  38:         }
  39:  
  40:         System.Diagnostics.Debug.WriteLine(message);
  41:     }
  42: }

If you run the method you’ll see that each element can now walk up it’s hierarchy to get it’s ancestry.

These methods could be extended to support all the options that the deep enumerator does, but I’ve not done so in the interest of brevity. Note I also could have used the Tuple class for this, but I chose to create my own for clarity.

No comments: