Florian
Florian

Reputation: 4728

Handling hierarchical collection with Linq

I have a hierarchical menu. The menu items looks like this :

public struct MenuElement
{
    public int Id {get; set;}
    public int Position {get; set;}
    public string Label {get; set;}
    public int HierarchicalLevel {get; set;}
    public int ParentLevelId {get; set;}
    public bool IsMandatory {get; set;}
}

The structure of my menu is managed with a node class :

public class Node<T>
{
   public T Item {get; set;}
   public IEnumerable<Node<T>> ChildrenNodes {get; set;}
   public int HierarchicalLevel {get; set;}
}

The menu items are retrieved from database. So, when I build my menu, and I browse my menu :

// Get the menu items from database
List<MenuElement> flattenMenuElements = GetMenuItemsFromDb();

// Build the hierarchical menu with relationships between nodes (parentId, ChildrenNodes...)
List<Node<MenuElement>> hierarchicalMenu = BuildMenu(flattenMenuElements);

foreach(var node in Browse(hierarchicalMenu))
{
     string space = ""

     for(int i=0; i<node.HierarchicalLevel; i++)
          space = String.Concat(space, " ");

     Console.Writeline("{0}{1}. {2}",space, node.Item.Position, node.Item.Label);
}

//Browse method
IEnumerable<Node<MenuElement>> Browse(IEnumerable<Node<MenuElement>> nodes)
{
     foreach(var node in nodes)
     {
         yield return node;
         foreach (var childNode in Browse(node.ChildrenNodes))
         {
              yield return childNode;
         }
     }
}

The Console output :

1. LabelMenu1
 1. LabelMenu11
  1. LabelMenu111
  2. LabelMenu112
  3. LabelMenu113
 2. LabelMenu12
 3. LabelMenu13
2. LabelMenu2
3. LabelMenu3
 1. LabelMenu31
...

So the result is what I expect. But now I want to get only MenuElement with the property IsMandatory == false AND THEIR PARENTS (and their grand-parents etc). For example, In the menu above, only the LabelMenu112 and LabelMenu31 has the property IsMandatory set to false. So I want if I browse my menu the output result will be like this :

1. LabelMenu1
 1. LabelMenu11
  2. LabelMenu112
3. LabelMenu3
 1. LabelMenu31

Actually, to do this, I rebuild a second menu from the first hierarchical menu after filtering on menu elements I want to keep :

// Get the menu elements from database
List<MenuElement> flattenMenuElements = GetMenuItemsFromDb();

// Build the hierarchical menu with relationships between nodes (parentId, ChildrenNodes...)
List<Node<MenuElement>> hierarchicalMenu = BuildMenu(flattenMenuElements);

// Get a flat list of menu elements where the property IsMandatory is set to false
List<MenuElement> filteredMenuElements = flattenMenuElements.Where(m => m.IsMandatory == false).ToList();

// Get a flat list of filtered menu elements AND THEIR PARENTS, GRAND PARENTS etc
List<MenuElement> filteredMenuElementsWithParents = GetMenuElementsWithParents(hierarchicalMenu, filteredMenuElements).ToList();


List<MenuElement> GetMenuElementsWithParents(IEnumerable<Node<MenuElement>> hierarchicalMenu, IEnumerable<MenuElement> filteredMenuElements)
{
     List<MenuElement> menu = new List<MenuElement>();
     foreach (var item in filteredMenuElements)
     {
          menu.Add(item);
          AddParentNode(item, menu, hierarchicalMenu);
     }
}

void AddParentNode(MenuElement element, List<MenuElement> menu, IEnumerable<Node<MenuElement>> hierarchicalMenu)
{
    if (element.ParentLevelId != default(int))
    {
        // Get the parent node of element
        MenuElement menuEl = Browse(hierarchicalMenu)
                               .Where(node => node.Item.Id == element.ParentLevelId)
                               .Select(node => node.Item)
                               .First();

        if(!menu.Contains(menuEl))
            menu.Add(menuEl);

        AddParentNode(menuEl, menu, hierarchicalMenu);             
    }
}

This solution works but I wonder if it's note possible to use the power of linq to retrieve this filtered menu elements and their parents rather than build a flat list, then build a second hierarchical menu from the flat list.

Is there a way to do this using Linq ?

Thank you !

Regards,

Florian

Upvotes: 1

Views: 916

Answers (1)

Alex Siepman
Alex Siepman

Reputation: 2598

It would be easier to use this Node class.

Node<MenuElement> rootNode = <Any node of the collection>.Root;

var mandatoryNodes = rootNode.SelfAndDescendants.Where(n => n.Value.IsMandatory);

foreach (var mandatoryNode in mandatoryNodes)
{
    foreach (var node in mandatoryNode.SelfAndAncestors.Reverse()) // Reverse because you want from root to node
    {
        var spaces = string.Empty.PadLeft(node.Level); // Replaces: for(int i=0; i<node.HierarchicalLevel; i++) space = String.Concat(space, " ");
        Console.WriteLine("{0}{1}. {2}", spaces, node.Value.Position, node.Value.Label);
    } 
}

Upvotes: 1

Related Questions