public NonLeafTreeNodeVM BuildChoiceTree(string rootGroupName, LayerClassVM[] classes) { NonLeafTreeNodeVM root = new NonLeafTreeNodeVM(rootGroupName, new NonLeafTreeNodeVM[0]); foreach (LayerClassVM vm in classes) { string[] path = vm.ID.Split(new char[] { Splitter }); PushClassToTree(root, path, vm); } return(root); }
/// <summary> /// Adds a class <paramref name="data"/> to the <paramref name="tree"/> (modifies the content of the tree) to the location in tree defined by <paramref name="classLocationPath"/> /// </summary> /// <param name="tree">What tree to push to</param> /// <param name="classLocationPath">A sequence of group names. The last element is an ID of the leaf node</param> /// <param name="data">What data to save in a new leaf node</param> private static void PushClassToTree(NonLeafTreeNodeVM tree, string[] classLocationPath, LayerClassVM data) { if (classLocationPath.Length == 0) { throw new ArgumentException("classLocationPath must contain at least one element"); } var children = new List <SelectionTreeNode>(tree.Children); if (classLocationPath.Length == 1) { //time to create leaf //constructing path to top List <NonLeafTreeNodeVM> pathToTop = new List <NonLeafTreeNodeVM>(tree.ChainToTop); pathToTop.Add(tree); LeafTreeNode leaf = new LeafTreeNode(data, pathToTop.ToArray()); children.Add(leaf); tree.Children = children.ToArray(); } else { //not a leaf node string groupName = classLocationPath[0]; string[] tail = classLocationPath.Skip(1).ToArray(); //is the non-leaf with the required group name already exists? var nonLeafs = tree.Children.Where(g => g is NonLeafTreeNodeVM).Select(g => (NonLeafTreeNodeVM)g); NonLeafTreeNodeVM node = nonLeafs.FirstOrDefault(g => g.GroupName == groupName); if (node == null) { //constructing path to top List <NonLeafTreeNodeVM> pathToTop = new List <NonLeafTreeNodeVM>(tree.ChainToTop); pathToTop.Add(tree); //we need to create a new non-leaf node as node with required group name is not exists node = new NonLeafTreeNodeVM(groupName, pathToTop.ToArray()); children.Add(node); tree.Children = children.ToArray(); } PushClassToTree(node, tail, data); } }