Interfaces / méthodes d'extension fluides - Conversion d'une liste non hiérarchique en arbre de navigation

StackOverflow https://stackoverflow.com/questions/807449

Question

J'ai actuellement une méthode d'extension qui convertit un IEnumerable de type Tab en une collection hiérarchique de TabNodes.

// If Tab has no parent its ParentId is -1

public class Tab
{
public int TabId { get; set; }
    public string TabName { get; set; }
    public int Level { get; set; }
    public int ParentId { get; set; }

}

public class TabNode
{
    public TabInfo Tab { get; set; }
    public IEnumerable<TabNode> ChildNodes { get; set; }
    public int Depth { get; set; }
}

Par exemple, ce qui suit vous donnerait une collection de TabNodes situés sous un parent avec TabId 32 - le niveau maximal de profondeur est de 4.

IEnumerable<Tab> tabs = GetTabs();

IEnumerable<TabNode> = tabs.AsNavigationHierarchy(32,4);

C'est déroutant et pas très amical pour plus de raffinement. Que se passe-t-il si je souhaite spécifier un certain niveau au lieu d'un ID parent?

Ce que j'aimerais faire est quelque chose comme ceci:

IEnumerable<TabNode> = tabs.AsNavigationHierarchy().WithStartLevel(2).WithMaxDepth(5)

Je suis coincé pour savoir comment faire cela avec élégance. Pouvez-vous m'aider?

C’est ma fonction actuelle appelée par mes méthodes d’extension (basée sur un article que j’ai trouvé sur www.scip.be ).

    private static IEnumerable<TabNode>
      CreateHierarchy(
        IEnumerable<TabInfo> tabs,
        int startTabId,
        int maxDepth,
        int depth)
    {
        IEnumerable<TabInfo> children;


            children = tabs.Where(i => i.ParentId.Equals(startTabId));


        if (children.Count() > 0)
        {
            depth++;

            if ((depth <= maxDepth) || (maxDepth == 0))
            {
                foreach (var childTab in children)
                    yield return
                      new TabNode()
                      {
                          Tab = childTab,
                          ChildNodes =
                            CreateHierarchy(tabs, childTab.TabID, maxDepth, depth),
                          Depth = depth
                      };
            }
        }
    }
Était-ce utile?

La solution

tabs.AsNavigationHeirachy peut renvoyer un objet HerirchyQuery auquel vos prochaines méthodes d'extension s'attendent. Cela vous permettra de les enchaîner.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top