2016-05-15 10 views
0

在過去的2天裏,我一直試圖計算C#中特定父代下的子節點。基本上我在我的數據庫中有一個SQL表,它有2列:user_id,Users_parentId。例如:如何計算C#中特定父項下的子節點總數?

__________________________ 
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

  • 基本上,我嘗試使用獲取子列表,然後數他們的孩子,如果他們再次抓住grand_child孩子的名單,等等,遞歸。

  • 我曾嘗試使用循環和foreach循環,但沒有找到解決方案。

  • 我想在頁面加載事件中統計總子(意味着現在100包含14個孩子)。

  • 當用戶登錄時,當時我想計算所有在他下面的孩子。

  • 我使用實體框架和LINQ訪問數據庫,我的數據庫名字爲GetUnitedDB,tablename是Office_Detail

  • 如果有上面提供任何錯誤或不完整的信息,請通知我。並請在C#中建議使用邏輯。

回答

1

您可以使用以下模板添加視圖到您的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; 
    } 
+0

好吧,但我想它在C#...所以你能不能幫我在C# –

+0

什麼是_UserTree_您在代碼中使用...? –

+0

檢查更新 – Moshezaurus

相關問題