I have an existing class :
public class Product
{
public int Id { get; set; }
public int ParentId { get; set; }
public string Info { get; set; }
}
And I also have a given List<Product>
:
var Lst = new List<Product>();
Lst.Add(new Product{ Id=1,ParentId=0,Info="a"});
Lst.Add(new Product{ Id=2,ParentId=0,Info="a"});
Lst.Add(new Product{ Id=3,ParentId=0,Info="a"});
Lst.Add(new Product{ Id=60,ParentId=1,Info="a"});
Lst.Add(new Product{ Id=61,ParentId=1,Info="a"});
Lst.Add(new Product{ Id=62,ParentId=61,Info="a"});
Lst.Add(new Product{ Id=72,ParentId=61,Info="a"});
Lst.Add(new Product{ Id=90,ParentId=2,Info="a"});
Visualization :
1
|
+---60
|
+---61
|
+---62
|
+---72
2
|
+---90
3
As you can see , the List<>
is flat. (all items are in the same level within the list. it's just that the id,parentId
represents heirarchy)
Now - I need to create structural List<>
so each item in List
will be inside its parent object :
so I created an additional structure class which will hold this structure :
public class Node
{
public Product Product { get; set; }
public List<Node> LstNodes { get; set; }
}
So now I can do :
List<Node> lstNodes = new List<Node>();
And initially I can add the root ones :
lstNodes=Lst.Where(product=>product.ParentId==0).Select(node=>new Node{Product=node}).ToList();
And now I can start recursion to insert items with their parents.
So Where is the problem ?
Question:
I want to avoid insertion of root elements first ( root is where ParentId=0
).
Is there any way of doing this with one recursive method (including roots) ?
Desired result : 3 nodes in lstNodes
where each has its children recursively.