2012-12-21 65 views
1

目錄樹節點我有了這些數據實施ExtJS的樹

State  Cities 

TX   Houston 
TX   San Antonio 
TX   Austin 
TX   Austin 
PA   Philadelphia 
PA   Pitssburgh 
PA   Pittsburgh 
PA   
CO   Boulder 
CO   Denver 

表我試圖實現具有這三種狀態爲節點和各城市爲葉一棵樹。

關於c#我正在創建一個列表。

  comd.CommandText = "SELECT * FROM MyTable"; 

      con.Open(); 
      SqlDataReader reader = comd.ExecuteReader(); 
      while (reader.Read()) 
      { 
       City myData = new City(); 
       myData.State = reader["State"].ToString().Trim(); 
       myData.Cities = reader["Cities"].ToString().Trim(); 
       giveData.Add(myData); 
      } 
      int count = 1; 
      List<TreeNode> myNode = new List<TreeNode>(); 
      foreach (City myData in giveData) 
      { 
       TreeNode treeNode = new TreeNode(); 
       treeNode.id = count++; 
       treeNode.name = myData.State; 
       treeNode.leaf = false; 

       List<TreeNode> Level1 = new List<TreeNode>(); 
       if (mydata.Cities != null) 
       { 
        if (mydata.Cities!= "") 
        { 
         foreach (City State in result) 
         { 
          TreeNode node1 = new TreeNode(); 
          node1.id = count++; 
          node1.name = myData.Cities; 
          node1.leaf = true; 

          Level1.Add(node1); 
         } 
        } 
       } 
       treeNode.children = Level1; 
       myNode.Add(treeNode); 
      } 

      return JsonConvert.SerializeObject(myNode); 

我所得到的是一個所有的4 TX和PA和2 CO樹中的節點,並在傳輸節點我得到兩個奧斯汀......

如何實現我的列表,以便我只得到一個TX,一個PA和一個CO和只有1個城市,如果有兩個城市...

回答

1

我無法測試,但應該這樣做:

comd.CommandText = "SELECT * FROM MyTable"; 

con.Open(); 
SqlDataReader reader = comd.ExecuteReader(); 
while (reader.Read()) 
{ 
    City myData = new City(); 
    myData.State = reader["State"].ToString().Trim(); 
    myData.Cities = reader["Cities"].ToString().Trim(); 
    giveData.Add(myData); 
} 
int count = 1; 
Dictionary<string, TreeNode> result = new Dictionary<string, TreeNode>(); 
foreach (City myData in giveData) 
{ 
    if (result.ContainsKey(myData.State)) 
    { 
     result[myData.State].children.Add(new TreeNode() { 
      id = count++, 
      name = myData.Cities, 
      leaf = true 
     }); 
    } 
    else 
    { 
     result.add(giveData.State, new TreeNode() { 
      id = count++, 
      name = myData.State, 
      leaf = false, 
      children = new List<TreeNode>() 
     }); 
    } 
} 

return JsonConvert.SerializeObject(result.Values); 
+0

由於SRA ...這看起來像比我試圖實現的更好的解決方案...將讓你知道它是否適用於我的方法...非常感謝sra ... – EagleFox

+0

嗨Sra ...我無法弄清楚你在其他語句中試圖做什麼..這是一個錯字嗎? on result.add(giveData.State,) – EagleFox

+1

@EagleFox是的,有一個錯字。再次檢查。 – sra