如何计算C#中特定父节点下的子节点总数



在过去的两天里,我一直在尝试计算C#中特定父节点下的子节点。基本上,我的数据库中有一个SQL表,它有两列:user_id、Users_parentId。示例:

__________________________
User_Id | Users_parentId
__________________________
100     | Noparent(main)
--------------------------
101     | 100(first User)
--------------------------
102     | 100
--------------------------
103     | 100
--------------------------
104     | 102 (3rd User)
--------------------------
105     | 100
--------------------------
106     | 102
--------------------------
107     | 102
--------------------------
111     | 107 (8th user)
--------------------------
112     | 107
--------------------------
115     | 105 (6th user)
--------------------------
222     | 105 
--------------------------
225     | 112
--------------------------
336     | 112
--------------------------
666     | 112
  • 如果我们从上表生成一个树,那么它将看起来像这样:

                         100
                ----------^-------------
                |    |       |        |
              101   102     103      105
             --------^------      ----^--------
             |     |     |         |         |
            104   106   107       115       222
                   ------^-----
                   |          |
                  111        112
                        ------^------
                        |     |     |
                      225    336   666
    
  • 因此,在我的项目中,我想计算所有孩子都在100之下

  • 基本上,我尝试使用get-child列表,然后计算他们的子列表,如果他们有,然后再次获取grand_child的子列表等等,递归地。

  • 我尝试过使用for循环和foreach循环,但没有找到解决方案。

  • 我想在页面加载事件中计数总子项(意味着现在100包含14个子项)。

  • 当用户登录时,我想计算他下面的所有孩子。

  • 我正在使用实体框架和LINQ访问数据库,我的数据库名称为GetUnitedDB,表名称为
    Office_Detail

  • 如果上面提供的信息有任何错误或不完整,请通知我。请在C#中建议逻辑。

您可以使用以下模板将视图添加到SQL数据库中:

;WITH UserTree AS
        (
            SELECT tn.User_Id UserId, tn.Users_parentId UserParentId, 0 AreaLevel
                FROM Office_Detail tn
                WHERE tn.Users_parentId = 100
            UNION ALL
                SELECT tn.User_Id, tn.Users_parentId, at.AreaLevel+1 AreaLevel
                FROM UserTree at
                    INNER JOIN Office_Detail tn on at.UserId = cn.Users_parentId                    
        )
        select COUNT(UserId)
        from UserTree   

还可以考虑将100值更改为user_id所使用类型的参数,并在视图的请求中发送它。

(此模板也可用于创建具有级别的树)

带有递归的C#实现:

private static int Count(int OriginalId)
    {
        using (var ctx = new YourDBContext())
        {
            return FindAllSons(OriginalId, ctx);
        }
    }
    private static int FindAllSons(int id, YourDBContext ctx)
    {
        var res = 1;
        var children = ctx.TableName.Where(x => x.ParentId == id).Select(n => n.Id);
        foreach(var child in children)
        {
            res += FindAllSons(child, ctx);
        }
        return res;
    }

最新更新