Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to traverse a tree with multiple branches

I'm working on an experimental TreeView where each TreeViewItem can either represent a condition, or a branch with an operator. This is to be parsed into SQL.

For example, the tree could have a branch with an "AND" or an "OR" operator, whose children would then be conditions. This is used to as to be able to generate the WHERE segment of an SQL statement, for example ((Name = 'Matt' AND AGE > 20) OR (Name = 'John' AND Age = 15)) AND Job = 'Student'.

How can I go about constructing that? What I've done so far is thought about placing a string,list<Condition> pair in a Tuple<>, where the string represents the branch operator (AND/OR), and the list represents the conditions contained within that branch.

However, since each branch can be split into a number of operator branches or conditions, it can get extremely complicated very quickly

like image 941
Dot NET Avatar asked Jan 21 '26 11:01

Dot NET


1 Answers

You can use recursive function to parse the treeview from top, so each root note of the treeview is one SQL statement:

e.g.:

enter image description here

function code:  

string getHead(TreeViewItem t)
            {
                string s = "";
                if (t.Items.Count == 0) //get the condition
                {
                    return s=t.Header.ToString(); //change this to your real getCondition function.
                }
                else
                {
                    for (int i = 0; i < t.Items.Count; i++ )
                    {
                        if(t.Items[i] is TreeViewItem) //Edit: only use treeviewitems not the button...
                        {
                          if (i == 0) // first note doesn't need the operator 
                          {
                            s += getHead(t.Items[0] as TreeViewItem);
                          }
                          else // only needs operator in between
                          {
                             s += (string.IsNullOrEmpty(getHead(t.Items[i] as TreeViewItem).Trim()) ? "" : (" " + t.Header + " " + getHead(t.Items[i] as TreeViewItem))); // only get real treeviewitem, not the one with two buttons and an empty header; change t.Header to your real getOperator function.

                          }
                        }                    
                    }
                    return string.Format("({0})",s); //group sub conditions
                }
            }

usage:

MessageBox.Show(getHead((treeView1.Items[0] as TreeViewItem)));

result:

enter image description here

like image 174
Bolu Avatar answered Jan 24 '26 17:01

Bolu