c# - How to transform list of hierarchyid into a binary tree -
i working on multi-level marketing (binary) looks this:
(but binary tree not required perfect. node can have 0-2 child)
my problem data fetch database flat list.
notice using hierarchyid (sql server 2014)
basically textnode
column breadcrumb.
every slash /
represents level
.
if have textnode of /1/
root. every node starts /1/
belongs root /1/
, /1/1/
, /1/1/1/
(the root node included level 0)
i've tried accepted answer in question not working.
how can transform flatlist binary tree can traverse , display on screen?
im using c#, asp mvc 5, sql server 2014 if matters.
here simple implementation (assuming nodes in right order), may enhanced in multiple ways
public interface irow<out t> { string textnode { get; } t value { get; } } public class treenode<t> { private struct nodedescriptor { public int level { get; } public int parentindex { get; } public nodedescriptor(irow<t> row) { var split = row.textnode.split(new [] {"/"}, stringsplitoptions.removeemptyentries); level = split.length; parentindex = split.length > 1 ? int.parse(split[split.length - 2]) - 1 : 0; } } public t value { get; } public list<treenode<t>> descendants { get; } private treenode(t value) { value = value; descendants = new list<treenode<t>>(); } public static treenode<t> parse(ireadonlylist<irow<t>> rows) { if (rows.count == 0) return null; var result = new treenode<t>(rows[0].value); fillparents(new[] {result}, rows, 1, 1); return result; } private static void fillparents(ilist<treenode<t>> parents, ireadonlylist<irow<t>> rows, int index, int currentlevel) { var result = new list<treenode<t>>(); (int = index; < rows.count; i++) { var descriptor = new nodedescriptor(rows[i]); if (descriptor.level != currentlevel) { fillparents(result, rows, i, descriptor.level); return; } var treenode = new treenode<t>(rows[i].value); parents[descriptor.parentindex].descendants.add(treenode); result.add(treenode); } } }
sample usage:
public class row : irow<string> { public string textnode { get; } public string value { get; } public row(string textnode, string username) { textnode = textnode; value = username; } } class program { static void main(string[] args) { irow<string>[] rows = { new row("/", "ahmed"), new row("/1/", "saeed"), new row("/2/", "amjid"), new row("/1/1/", "noura"), new row("/2/1/", "noura01"), new row("/2/2/", "reem01"), new row("/1/1/1", "under_noura") }; var tree = treenode<string>.parse(rows); printtree(tree); } private static void printtree<t>(treenode<t> tree, int level = 0) { string prefix = new string('-', level*2); console.writeline("{0}{1}", prefix, tree.value); foreach (var node in tree.descendants) { printtree(node, level + 1); } } }
Comments
Post a Comment