【问题标题】:Automating the Tree Traversal in C#在 C# 中自动遍历树
【发布时间】:2012-06-04 01:37:43
【问题描述】:

朋友们好!目前我正在研究这个数据库模型设计,称为修改前序树遍历(MPTT)。在看到使用通用表表达式 (CTE) 的劣势后,我发现了使用 MPTT 的建议。但在我可以使用 MPTT 的好处之前,我需要通过添加“右”和“左”节点值来重新设计我的数据库表。为此,我需要制作一个程序来自动化和更新表中每个数据的值。我的问题是我无法制作一个自动化节点值的程序。我正在尝试将 php 语言转换为 C# 代码,但我做不到。我在编程中的一个弱点是创建“递归”方法。

我使用这个链接作为我的参考。 Hierarchical database model

这是我尝试转换为 C# 的代码

<?php 
function rebuild_tree($parent, $left) {   
    // the right value of this node is the left value + 1   
    $right = $left+1;   

    // get all children of this node   
    $result = mysql_query('SELECT title FROM tree '.   
                           'WHERE parent="'.$parent.'";');  
    while ($row = mysql_fetch_array($result)) {   
        // recursive execution of this function for each   
        // child of this node   
        // $right is the current right value, which is   
        // incremented by the rebuild_tree function   
        $right = rebuild_tree($row['title'], $right);   
    }   

    // we've got the left value, and now that we've processed
    // the children of this node we also know the right value   
    mysql_query('UPDATE tree SET lft='.$left.', rgt='.   
                 $right.' WHERE title="'.$parent.'";');   

    // return the right value of this node + 1   
    return $right+1;   
}   
?>

【问题讨论】:

  • 您的具体问题是什么? C# 和 PHP 通常非常相似,您的代码也不例外。这段代码的转换应该很简单。

标签: c# recursive-query mptt


【解决方案1】:

这是我自己的代码,如果有更好的解决方案,请告诉我

    int right = 0;

    public int rebuild_tree(int parent, int left)
    {
        // the right value of this node is the left value + 1
        right = left + 1;

        // get all children of this node
        command = conn.CreateCommand();
        command.CommandText = "SELECT cat_id FROM tbl_RefDataCategory_mst WHERE parent_id=@parent";
        command.Parameters.Add("parent", SqlDbType.Int).Value = parent;

        using (SqlDataReader reader = command.ExecuteReader())
        {
            while (reader.Read())
            {
                int temp = Convert.ToInt32(reader["cat_id"]);
                right = rebuild_tree(temp, right);
            }

            command = conn.CreateCommand();
            command.CommandText = "UPDATE tbl_RefDataCategory_mst SET lft=@l, rgt=@r WHERE cat_id=@p";
            command.Parameters.Add("l", SqlDbType.Int).Value = left;
            command.Parameters.Add("r", SqlDbType.Int).Value = right;
            command.Parameters.Add("p", SqlDbType.Int).Value = parent;

            command.ExecuteNonQuery();
        }

        return right + 1;
    }

【讨论】:

    猜你喜欢
    • 2012-09-12
    • 1970-01-01
    • 1970-01-01
    • 2010-12-30
    • 1970-01-01
    • 2011-05-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多