2012-11-20 30 views
0

我嘗試嘗試遞歸,並且在遞歸函數中使用ArrayList時出現問題。這個問題是基於另一個寫的HERE,但不是創建一個TreeView,我嘗試插入類別的ID,並得到它的孩子,subchildren ..等;屬於這個類別。我用的是函數的代碼如下:使用ArrayList遞歸,問題ASP.NET

ArrayList arr = new ArrayList(); 
    List<MyObject> list = new List<MyObject>(); 
     list.Add(new MyObject() { Id = 1, Name = "Alice", ParentId = 0 }); 
     list.Add(new MyObject() { Id = 2, Name = "Bob", ParentId = 1 }); 
     list.Add(new MyObject() { Id = 3, Name = "Charlie", ParentId = 1 }); 
     list.Add(new MyObject() { Id = 4, Name = "David", ParentId = 2 }); 

    if (idCategory != "") //This is taken from querystring 
    { 
     int a = int.Parse(idCategorie); 
     arr = GetCategs(list, a); 
     foreach (int vvv in arr) 
     { 
      Label3.Text += " " + vvv.ToString(); 
     } 
    } 

private ArrayList GetCategs(IEnumerable<MyObject> list, int parentNode) 
{ 
    ArrayList arls = new ArrayList(); 
    var nodes = list.Where(x => x.ParentId == parentNode); 
    foreach (var node in nodes) 
    { 
     int newNode = node.Id; 
     arls.Add(newNode); 
     Label1.Text += " " + newNode.ToString(); 
     GetCategs(list, newNode); 
    } 
    foreach (int cvcv in arls) 
    { 
     Label2.Text += " " + cvcv.ToString(); 
    } 
    return arls; 
} 

所以我通過列表(see the example i mentioned to understand where the list comes from)和類別(或子類別)的id,我需要。我使用ArrayList來捕獲所有兒童的ID並將其插入到名爲arls的arrayList中。僅用於測試目的,我使用Label1 Label2和Label3。當我運行代碼時,Label1向我展示了以下所有級別的所有孩子的所有ID,Label2向我展示了相同的結果(這表示成功通過arsl的ID),而Label3只顯示了ID的1級的孩子不是2級(孫輩)或3級(高等的兒童)。問題是:什麼問題?它如何解決。 謝謝。

+1

看起來你的原始列表中沒有孫子,greatgrandchildren。你可以發佈列表的價值嗎?此外,您不使用此遞歸方法的返回值。 –

+0

我改變了它一點點,所以我可以使用返回值。問題實際上是將該值返回給函數的調用者。我再測試一次! arls arraylist包含我需要的所有信息,而arr arraylist只包含一級孩子! – John

+0

似乎工作正常,我會確保'list'具有您所期望的值 – NKeddie

回答

0

我得到了答案。不是將ArrayList arls傳遞給ArrayList arr,而是直接啓動PageLoad,直接在函數內部使用它。所以現在代碼看起來像這樣:

ArrayList arr = new ArrayList();//Now it can be seen by the function GetCategs 
protected void Page_Load(object sender, EventArgs e) 
{ 

List<MyObject> list = new List<MyObject>(); 
list.Add(new MyObject() { Id = 1, Name = "Alice", ParentId = 0 }); 
list.Add(new MyObject() { Id = 2, Name = "Bob", ParentId = 1 }); 
list.Add(new MyObject() { Id = 3, Name = "Charlie", ParentId = 1 }); 
list.Add(new MyObject() { Id = 4, Name = "David", ParentId = 2 }); 

if (idCategory != "") //This is taken from querystring 
{ 
    int a = int.Parse(idCategory); 
    GetCategs(list, a); 
    foreach (int vvv in arr) 
    { 
     Label3.Text += " " + vvv.ToString(); 
    } 
} 
} 
private void GetCategs(IEnumerable<MyObject> list, int parentNode) 
{ 

    var nodes = list.Where(x => x.ParentId == parentNode); 
    foreach (var node in nodes) 
    { 
     int newNode = node.Id; 
     arls.Add(newNode); 
     Label1.Text += " " + newNode.ToString(); 
     GetCategs(list, newNode); 
    } 
}