I have a list that contains parent child relation and I want to get children upto defined length:
Given the following class:
public class Item
{
public int Id { get; set; }
public string Name { get; set; }
public int ParentId { get; set; }
}
Here is the list:
var list = new List<Item>();
list.Add(new Item { Id = 1, Name = "Parent", ParentId = 0 });
list.Add(new Item { Id = 2, Name = "Child1", ParentId = 1 });
list.Add(new Item { Id = 3, Name = "Child2", ParentId = 1 });
list.Add(new Item { Id = 4, Name = "GrandChild1", ParentId = 2 });
list.Add(new Item { Id = 5, Name = "GrandChild2", ParentId = 2 });
list.Add(new Item { Id = 6, Name = "GrandChild3", ParentId = 3 });
list.Add(new Item { Id = 7, Name = "GrandChild4", ParentId = 3 });
list.Add(new Item { Id = 8, Name = "GrandGrandChild1", ParentId = 4 });
list.Add(new Item { Id = 9, Name = "GrandGrandChild2", ParentId = 5 });
list.Add(new Item { Id = 10, Name = "GrandGrandChild3", ParentId = 6 });
list.Add(new Item { Id = 11, Name = "GrandGrandChild4", ParentId = 7 });
Now I want that if I pass depth=0 in url then it will return all data but if I pass depth=1 then it will return string like:
"Parent:Child1:GrandChild1:GrandGrandChild1"
"Parent:Child1:GrandChild2:GrandGrandChild2"
and if I pass depth=2 then:
"Parent:Child1:GrandChild1:GrandGrandChild1"
I have tried this code:
public void Traverse(List<Item> list)
{
var parentIds = list.Where(e => e.ParentId > 0).Select(e => e.ParentId).ToList();
var bargs = list.Where(e => !parentIds.Contains(e.Id)).ToList();
foreach (var item in bargs)
{
Traverse(list, item);
}
}
private void Traverse(List<Item> items, Item item)
{
var list = new List<Item> { item };
int id = item.ParentId;
while (true)
{
var found = items.Where(e => e.Id == id).FirstOrDefault();
list.Insert(0, found);
if(found.ParentId == 0) { break; }
id = found.ParentId;
}
var str = string.Empty;
foreach (var node in list)
{
str += node.Name;
if(node != item) { str += ":"; }
}
Console.WriteLine(str);
}
Now this code returns the desired strings successfully but I can't figure out how can I add depth check in "items". Depth can be "n" so I can't add if else. Any help?
See Question&Answers more detail:
os