Reputation:
I have a parent-child list. It can be of n-level.
I need each item within this hierarchy.
I am using 'foreach' loop and recursive function but it's not working.
I have went through other solutions at 'stackoverflow' but none of them worked for me.
public class Item
{
public int Id { get; set; }
public string Name { get; set; }
public int ParentId { get; set; }
private List<Item> children = new List<Item>();
public List<Item> Children
{
get { return children; }
set { children = value; }
}
}
List<Item> test = new List<Item>();
test.Add(new Item { Id = 1, Name = "Root1", ParentId = -1 });
test[0].Children.Add(new Item { Id = 4, Name = "child-1-Root1", ParentId = 1 });
test[0].Children[0].Children.Add(new Item { Id = 10, Name = "grandchild-1-Root1", ParentId = 4 });
test[0].Children.Add(new Item { Id = 5, Name = "child-2-Root1", ParentId = 1 });
test.Add(new Item { Id = 2, Name = "Root2", ParentId = -1 });
test[1].Children.Add(new Item { Id = 6, Name = "child-1-Root2", ParentId = 2 });
test[1].Children.Add(new Item { Id = 7, Name = "child-2-Root2", ParentId = 2 });
test.Add(new Item { Id = 3, Name = "Root3", ParentId = -1 });
test[2].Children.Add(new Item { Id = 8, Name = "child-1-Root3", ParentId = 3 });
test[2].Children.Add(new Item { Id = 9, Name = "child-2-Root3", ParentId = 3 });
Upvotes: 1
Views: 2373
Reputation:
The solution is:
public static Find()
{
foreach (var item in test)
{
FindRecursively(item, item.Name);
}
}
public static Item FindRecursively(Item node, string name)
{
if (node == null)
return null;
if (node.Name == name)
Console.WriteLine(node.Name);
foreach (var child in node.Children)
{
var found = FindRecursively(child, child.Name);
}
return null;
}
Upvotes: 1