public NavTreeViewModel Build() { var leafIndex = 1; var treeRootNode = TreeItem <NavTreeItemModel> .CreateParentNode("root", Array.Empty <TreeItem <NavTreeItemModel> >()); foreach (var state in _internalState) { AddNavTreeItem(state, treeRootNode); } return(new NavTreeViewModel ( treeRootNode.Children, treeRootNode.Children.GetFirstSelectableTestState(), Enumerable.Empty <TreeItem <NavTreeItemModel> >() )); void AddNavTreeItem(InternalStateItem state, TreeItem <NavTreeItemModel> parentNode) { var nodes = state.NodeTitle.Split('/'); var currentTitle = nodes[0]; var currentNode = parentNode.Children.SingleOrDefault(o => o.DisplayName == currentTitle); var currentNodeExists = currentNode != null; var isLeafNode = nodes.Length == 1; //Leaf Node if (isLeafNode) { var leafChild = TreeItem <NavTreeItemModel> .CreateLeafNode(leafIndex, currentTitle, state.Type, new NavTreeItemModel(state.ViewModel, state.IsCarltonComponent)); parentNode.Children = parentNode.Children.Append(leafChild); leafIndex++; return; } //Parent Does Not Exist if (!currentNodeExists) { var newNode = TreeItem <NavTreeItemModel> .CreateParentNode(currentTitle, Array.Empty <TreeItem <NavTreeItemModel> >()); parentNode.Children = parentNode.Children.Append(newNode); currentNode = newNode; } //Move to the Next Node state.PopCurrentFromNodeTitle(); AddNavTreeItem(state, currentNode); }; }