Note that there are some explanatory texts on larger screens.

plurals
  1. POC# Large Tree Iteration
    primarykey
    data
    text
    <p>I have a large result set assembled in a parent/child relationship. I need to walk the tree and display the results to the user. </p> <p>I've done this before using recursion, but because my result set may be large, I want to avoid the possibility of receiving a StackOverflowException.</p> <p>I found the following <a href="http://msdn.microsoft.com/en-us/library/bb513869.aspx" rel="nofollow noreferrer">example</a> on MSDN which uses a Stack. The problem I'm having is because a stack is last-in first-out, my data doesn't appear properly. I'd like it to look like the following:</p> <pre><code> LeveL 1 Level 1.1 Level 1.1.1 Level 1.1.2 Level 1.2 Level 1.2.1 Level 1.2.2 </code></pre> <p>But it looks like:</p> <pre><code> LeveL 1 Level 1.2 Level 1.2.2 Level 1.2.1 Level 1.1 Level 1.1.2 Level 1.1.1 </code></pre> <p>Any ideas?</p> <p>Here is an example of my code. Assuming the <code>DataTable dt</code> has the following columns: ID, ParentID, and Text</p> <pre><code> private struct Item { public string Text; public int ID; public int ParentID; } private void BuildView() { Stack&lt;Item&gt; itemTree = new Stack&lt;Item&gt;(40); //Get All Parent Nodes DataView dv = new DataView(dt); dv.RowFilter = "ParentID = 0"; //Add the parent nodes to the stack foreach (DataRowView drv in dv) { Item item = new Item(); item.Text = drv["Text"].ToString(); item.ID = drv["ID"].ToString(); item.ParentID = drv["ParentID"].ToString(); itemTree.Push(item); } //Go through the stack one node at a time while (itemTree.Count &gt; 0) { Item currentItem = itemTree.Pop(); Debug.WriteLine(currentItem.Text); //Get children of current node dv.RowFilter = String.Format("ParentID = {0}", currentItem.ID); if (dv.Count &gt; 0) { //Add child nodes to the stack foreach (DataRowView drvChild in dv) { Item item = new Item(); item.Text = drvChild["Text"].ToString(); item.ID = drvChild["ID"].ToString(); item.ParentID = drvChild["ParentID"].ToString(); itemTree.Push(item); } } } } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload