private static TreeElement BuildTree(this TreeElement root, List <TreeElement> elements) { if (elements.Count == 0) { return(root); } var children = root.FetchChildren(elements).ToList(); root.Children.AddRange(children); root.RemoveChildren(elements); for (int i = 0; i < children.Count; i++) { children[i] = children[i].BuildTree(elements); if (elements.Count == 0) { break; } } return(root); }