【问题标题】:How to traverse a tree with multiple branches如何遍历具有多个分支的树
【发布时间】:2023-04-05 03:20:02
【问题描述】:

我正在开发一个实验性的 TreeView,其中每个 TreeViewItem 可以表示一个条件,也可以表示一个带有运算符的分支。这是要解析成SQL的。

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

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

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

【问题讨论】:

  • 你可能需要一个树形数据结构:stackoverflow.com/questions/66893/…
  • treeview 是否已经在那里供您解析,还是您也需要构建 treeview
  • @Bolu TreeView 已经在那里供我解析

标签: c# .net sql wpf algorithm


【解决方案1】:

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

例如:

功能代码:

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)));

结果:

【讨论】:

  • 感谢您的回复。不幸的是,在每个分支之后,我都有一个带有按钮的 TreeViewItem。它怎么能跳过它并且仍然递归地工作?
  • @DotNET,已更新,需要添加if(t.Items[i] is TreeViewItem)
  • 再次嗨,我几乎可以正常工作了。出于某种原因,它一直在末尾添加“AND”或“OR”。所以我得到了类似(ID=5 AND Name=Matt AND)
  • @DotNET,您可以为treeview 发布您的xaml 吗?我猜你有一些空的treeviewitem(没有标题的项目)
  • 我没有任何 XAML,因为 TreeView 是由用户在运行时生成的。如果有帮助,我可以发布一张解释结构的图表吗?
【解决方案2】:

在您的树形视图中,最后一个 AND 和 OR 不应该互换吗?我无法使用该视图访问您在下面指定的相同解析字符串。

AND
    AND
         Job='Student'
         Age > 20
    AND
         OR
            Name='John'
            Name='Matt'
         Sex='Male'   

最后一个 AND 与另一个 OR 条件和单个语句。

不确定这是否有帮助,但 bison 会生成 C 代码以进行自下而上的解析,就像这样。你可以试试看。

e: conditional statement|
   e AND e|
   e OR e
;

【讨论】:

  • 我提供的只是一个例子。用户可以随意修改树
猜你喜欢
  • 2018-03-17
  • 2016-07-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-03-07
  • 1970-01-01
相关资源
最近更新 更多