c# - Query children and its children until there are no children simplified -


let's have entity following properties:

public class foo     {     public int id { get; set; }     public string name { get; set; }     public int? parentid { get; set; } } 

a child foo has non-null parentid. there can several levels of parent/child relationships, 5 @ point.

is there simple linq way or general methodology begin foo , of children, , children's children, , it's children's children's children, etc?

currently, i'm looping through each child of beginning parent, looping again of child's children, etc. tedious , doesn't appear correct way of accomplishing want.

i prefer maintain string property represents place in hierarchy. example, if value "/99/42" know item belongs parent 42 belongs 99. reason nice because can flatten out whole collection of foos , query field beginning "/99" , you'll entire branch of hierarchy. class this:

public class foo     {     public int id { get; set; }     public string name { get; set; }     public string path { get; set; } //eg: /99/42 } 

hope helps.


Comments