Using Linq to access I have a self-referencing collection in memory I would like to get all records that are beneath a given ID. I would also like to pass a depth level so it would not search children records after the level was reached. The level could help avoid a circular reference of self-referencing and endless loop
So here is my in memory object
ID NAME PARENTID
1 Bob null
2 Cody 1
3 Duke 1
4 Eric 2
5 Fred 4
6 Greg 5
Example if the user pass in the following ID=4 MAXLEVEL = 3 they would see the following results
4-Eric,
5-Fred,
6-Greg
The results should be flattened and not hierarchical. What would be the best approach using Linq thanks for you advise and help.
VulpesPosted Jan 20, 2014, 11:48 AM
As expected the output is:
If you create a circular reference by making Cody's ParentId = 5, then the output is:
So, the level parameter does prevent an endless loop (and hence a stack overflow here) as you anticipated and the Union method prevents duplicates being returned.
Lawrence PondPosted Jan 20, 2014, 8:45 PM
Biswa Pujarini MohapatraPosted Jan 20, 2014, 2:20 AM
check out this threads
http://stackoverflow.com/questions/5377114/what-is-the-best-way-to-get-the-level-from-a-tree-data-structure-using-linq
http://stackoverflow.com/questions/12243658/depth-first-flattened-collection-of-an-object-hierarchy-using-linq
http://stackoverflow.com/questions/17968069/linq-sort-a-flat-list-based-on-childorder
hope it helps