0

I'm looking for a examples on how to best iterate over a table with two cols; Parent and Child

Given a Parent, if a child is found I want to add it to a new List. Then I want to query again this time using the previous Child but now as the Parent to check if this child has children...and so on...

I hope this makes sense. Thanks in advance for your help.

I'm writing the queries in Linq against Entities.

Mustang31
  • 282
  • 1
  • 3
  • 15
  • This sounds like you want to do a recursive query using Linq to Entities. Possibly duplicate: http://stackoverflow.com/questions/1308158/how-does-entity-framework-work-with-recursive-hierarchies-include-seems-not-t – Corey Sunwold May 05 '12 at 06:31

1 Answers1

1

I believe you are looking for a way to recursively get the data from a self referencing table. Here is an article explaining Parent – Child in recursive data table with LINQ


From Article

var q=  from p in yourTable
     where p.ParentID == null  // well get all parents
      select new 
       {
             ParentID = p.ParentID,
            child =  from c in yourTable
                      where c.ParentID == p.ID select
                           new  {
                                ChildID=c.ID,
                                ParentID = c.ParentID
                                }
      };
Habib
  • 219,104
  • 29
  • 407
  • 436