Muhanad YOUNIS

Parent – Child in recursive data table with LINQ

If you have a data table which looks like this one below and holds child,parent rows at the same table;

ID ParentID Name
guid1 null parent 1
guid2 guid1 child for parent 1
so on so on so on

and you wont to retrieve all records from the table in a table looks like below;

Parent Childs
parent 1 child 1 for parent 1
child 2 for parent 1
child 3 for parent 1
….
Parent 2 child 1 for parent 2
child 2 for parent 2
….

This means that i have to make a recursive query in Sql to retrieve it this way. but with LINQ its more easy to be done, see the query below;

   1:  var q=  from p in TypedDataTable
   2:      where p.ParentID == null  // well get all parents
   3:      select new 
   4:       {
   5:             ParentID = p.ParentID,
   6:            child =  from c in TypedDataTable 
   7:                      where c.ParentID == p.ID select
                           new {ChildID=c.ID,
   8:                          ParentID = c.ParentID}
   9:      };
  10:          

and by the query above you’ll get this result;

linqParentChild 

 NOTICE : this query will load one level at a time

hope this helps

Posted: Nov 07 2009, 04:19 PM by mohi88 | with 5 comment(s)
Filed under: ,

Comments

adefwebserver said:

Wow. Linq is the greatest thing invented in a long time.

# November 7, 2009 6:07 PM

Parent ??? Child in recursive data table with LINQ - Muhanad YOUNIS | Dataentry update today said:

Pingback from  Parent ??? Child in recursive data table with LINQ - Muhanad YOUNIS | Dataentry update today

# November 7, 2009 9:51 PM

Servefault.com said:

Thank you for submitting this cool story - Trackback from Servefault.com

# November 8, 2009 12:34 AM

Dhananjay Goyani said:

Good one...

What if I want to get n-th level children or parent. Well, I don't think your example can fetch recursive results - it just populates parent child relations.


# November 9, 2009 5:40 AM

mohi88 said:

Dhananjay, thanks

you are right you can not get N level with this query, you must loop inside each child to see if you have a child for it. you can check here for more information

www.lowendahl.net/showShout.aspx

# November 9, 2009 7:20 AM
Leave a Comment

(required) 

(required) 

(optional)

(required)