I try to experiment with recursion, and I get a problem when using ArrayList in a recursive function. This question is based on the other one written HERE but instead of creating a TreeView i try to insert the category's id and get it's children, subchildren.. etc; that belong to this category. The code of the function I use is below:
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;
}
So i pass the list (see the example i mentioned to understand where the list comes from) and the id of the category (or subcategory) i need. I use an ArrayList to catch all the childrens' IDs and insert it into the arrayList called arls. Just for testing purposes i use Label1 Label2 and Label3. When i run the code, Label1 is showing me all the IDs of the children of all the levels below, Label2 is showing me the same results (this means that the IDs where successfully passe in the arsl) while Label3 is showing just the id's of the 1-st level children not the ones of the level2 (grandchildren) or level3(grandgrandchildren). The question is: What's the problem? how can it be solved. Thank You.
listhas the values you are expecting