如何计算C#中特定parent下的总child个节点?

How to count total child nodes under the specific parent in C#?

在过去的 2 天里,我一直在尝试计算 C# 中特定 parent 下的 child 节点。基本上我的数据库中有一个 SQL table,其中有 2 列: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

您可以使用以下模板向 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;
    }