gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:18:39 25 4
gpt4 key购买 nike

我正在研究一个实验性的 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com