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;
NOTICE : this query will load one level at a time
hope this helps