Recursive LINQ query

P

Peter Thorton

Hello,

I am trying to figure out how to write a LINQ query to a dataset to give
me a list of all x's parents recursively.

My table structure is:

id int
parent_id int (dbnull if the root node)
name string

I can easily get x's direct parents:
var tree = from parent in table where dataset.table.parent_id ==
parent.id
select parent.name;

I need all of x's grandparents, great grandparents, etc...

Thank you,
 
P

Pavel Minaev

Hello,

I am trying to figure out how to write a LINQ query to a dataset to give
me a list of all x's parents recursively.

My table structure is:

id          int
parent_id   int (dbnull if the root node)
name        string

I can easily get x's direct parents:
var tree = from parent in table where dataset.table.parent_id ==
parent.id
select parent.name;

I need all of x's grandparents, great grandparents, etc...

That's a classic stumbling block with relational-style queries (which
LINQ closely resembles). There are some tricks to do this efficiently
from SQL (e.g. see http://msdn.microsoft.com/en-us/library/ms186243.aspx
and http://technet.microsoft.com/en-us/library/bb677290.aspx), but
none that I know work in LINQ to SQL or LINQ to Entities. The best you
can do is query in a loop (or recursion), one iteration for each level
of the hierarchy, till you reach the top.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top