c# - 如何遍历具有多个分支的树

标签 c# .net sql wpf algorithm

我正在研究一个实验性的 TreeView,其中每个 TreeViewItem 都可以代表一个条件,或者代表一个带有运算符的分支。这将被解析为 SQL。

例如,树可以有一个带有“AND”或“OR”运算符的分支,其子项将成为条件。这用于生成 WHERE SQL 语句段,例如 ((Name = 'Matt' AND AGE > 20) OR (Name = 'John' AND Age = 15)) AND Job = 'Student' .

我该如何构建它?到目前为止我所做的是考虑放置一个 string,list<Condition>配对Tuple<> ,其中字符串表示分支运算符 (AND/OR),列表表示该分支中包含的条件。

但是,由于每个分支都可以拆分为多个运算符分支或条件,因此它会很快变得极其复杂

最佳答案

您可以使用递归函数从顶部解析treeview,因此treeview 的每个根注释都是一条SQL 语句:

例如:

enter image description here

功能代码:

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
                }
            }

用法:

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

结果:

enter image description here

关于c# - 如何遍历具有多个分支的树,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13911450/

相关文章:

c# - 存储库模式 - 如何结合数据库和内存中的实体?

c# - 网络编程和数据包交互

c# - 将构造函数参数传递给在 InitializeComponent 中创建的控件

c# - 掌上电脑 : Draw control to bitmap

mysql - 使用 group by 和 having 子句获取多个最大行

asp.net - 即使执行成功,ExecuteNonQuery 返回 -1

c# - 如何更新所有 blob 存储文件的 ContentDisposition 属性?

c# - 无法通过 Alamofire.upload multipartFormData 调用 Web Api

c# - DiagnosticDescriptor 构造函数的新参数的相关性?

mysql - 在Mysql中加入寄存器