Tuesday, August 01, 2006

Hierarchical iteration à la .NET 2.0

E.g. a foreach-iteration over the (sub)items of a (System.Web.UI.WebControls.)Menu or TreeView...

private delegate ICollection GetChildrenDelegate<T>(T parent);


private IEnumerable<T> getHierarchicalItems<T>(
   ICollection source
   ,GetChildrenDelegate<T> getChildren
   )
{
   Queue<T> q = new Queue<T>();
   ICollection childs = source;

   while (true)
   {
      foreach (T item in childs)
      {
         yield return item;

         if (getChildren(item).Count > 0)
         {
            q.Enqueue(item);
         }
      }

      if (0 == q.Count) { break; }
      childs = getChildren(q.Dequeue());
   }
}



Iteration over Menu/-Items
GetChildrenDelegate<MenuItem> getSubMenus =
   delegate(MenuItem current)
      {
         return current.ChildItems; 
      };

foreach (MenuItem item in this.getHierarchicalItems<MenuItem>(
   menu.Items
   , getSubMenus))
{
   ...
}



Iteration over Tree-View/-Nodes
GetChildrenDelegate<TreeNode> getSubNodes =
   delegate(TreeNode current)
      {
         return current.ChildNodes;
      };

foreach (TreeNode item in this.getHierarchicalItems<TreeNode>(
   tree.Nodes
   , getSubNodes))
{
   ...
}

No comments: