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.
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.
I found the following example 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:
LeveL 1 Level 1.1 Level 1.1.1 Level 1.1.2 Level 1.2 Level 1.2.1 Level 1.2.2
But it looks like:
LeveL 1 Level 1.2 Level 1.2.2 Level 1.2.1 Level 1.1 Level 1.1.2 Level 1.1.1
Any ideas?
Here is an example of my code. Assuming the DataTable dt has the following columns: ID, ParentID, and Text
private struct Item { public string Text; public int ID; public int ParentID; } private void BuildView() { Stack<Item> itemTree = new Stack<Item>(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 > 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 > 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); } } } }
Push your items onto the stack in the reverse order, i.e. 2 before 1.
Example:
To do this in your code, try the following
for-eachstatement: