使用ArrayList递归,问题ASP.NET

时间:2012-11-20 20:20:53

标签: asp.net recursion arraylist

我尝试尝试递归,在递归函数中使用ArrayList时出现问题。这个问题基于另一个写的HERE,但是我没有创建一个TreeView,而是尝试插入类别的id并获取它的子节点,子节点等等;属于这一类。我使用的函数的代码如下:

    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 个答案:

答案 0 :(得分:0)

我得到了答案。我没有将ArrayList arls传递给ArrayList arr,而是启动了PageLoad的arr ouside,并直接在函数内部使用它。所以现在代码看起来像这样:

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);
    }
}