Interfacce / metodi di estensione fluidi: trasformazione di un elenco semplice in un albero di navigazione
-
03-07-2019 - |
Domanda
Attualmente ho un metodo di estensione che converte un IEnumerable di tipo Tab in una raccolta gerarchica di 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; }
}
Ad esempio, quanto segue ti darebbe una raccolta di TabNodes che sono sotto un Parent con TabId 32 - il livello massimo di profondità è 4.
IEnumerable<Tab> tabs = GetTabs();
IEnumerable<TabNode> = tabs.AsNavigationHierarchy(32,4);
Questo è confuso e non molto amichevole per ulteriore raffinamento. Cosa succede se vorrei specificare un determinato livello anziché un ParentID?
Quello che mi piacerebbe fare è qualcosa del genere:
IEnumerable<TabNode> = tabs.AsNavigationHierarchy().WithStartLevel(2).WithMaxDepth(5)
Sono bloccato su come farlo elegantemente. Mi potete aiutare?
Questa è la mia attuale funzione che viene chiamata dai miei metodi di estensione (sulla base di un articolo che ho trovato su 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
};
}
}
}
Soluzione
tabs.AsNavigationHeirachy potrebbe restituire un oggetto HerirchyQuery che i tuoi successivi metodi di estensione si aspetterebbero. Questo ti permetterà di unirli insieme.