Linq recursive query

Hi Experts,

My Sql table looks like this:

I have a categoryId and I want to list all the parents up the root category.

I use linq and I know how to find the first parent category, but I want to find all the parents to get the complete path.

Thanks in advance for your help.
Who is Participating?
nouloukAuthor Commented:
Thanks Smart Man,

I already found those links, but it doesn't help me. It seems to be very difficult and not talk about linq to Sql.
var ParentCategory = from categories in dataContext.Categories
                                   where categories.CategoryId = categoryId
                                   select categories.ParentCategoryId

The recursion means to reuse this query to get the parent of this ParentCategoryId from my submitted CategoryId ...

Your link doesn't show any linq to Sql queries or could you tell me the way to implement such a recursive query?

Smart_ManConnect With a Mentor Commented:
it is about traversing operator

There has not been a recursive query operator defined yet for LINQ.  Of course, you've defined a cyclic data structure, so even if there were a recursive operator it would likely fail.


Here is a recursive traversal operator you could use.  It may have some typos.  It converts your deep hierarchy into a flat sequence.

public static class MyExtensions {

   public static IEnumerable<T> Traverse(this IEnumerable<T> source, Func<T, IEnumerable<T>> fnRecurse) {

           foreach(T item in source) {

                  yield return item;

                  IEnumerable<T> seqRecurse = fnRecurse(item);

                  if (seqRecurse != null) {

                      foreach(T itemRecurse in Traverse(seqRecurse, fnRecurse)) {

                         yield return itemRecurse;






To traverse all values in your collection:


List<MyClass> list = ...;


var total = list.Traverse(x => x.MyList).Sum(x => x.Val).

hope that is more helpfull. sorry the previous links did not worked for you.

let me know if you want the solution code supplied directly

waiting for your reply
nouloukAuthor Commented:
Thanks, your comments help me very much.

The main problem is I use Linq to SQL and using an extension as you tell is crazy.
For example, if I have 20 childs, Linq to SQL will query 20 requests againt the database !
So, as you suggest me I will use a stored procs with CTE.
All Courses

From novice to tech pro — start learning today.