Abe Miessler
Abe Miessler

Reputation: 85126

Using LINQ to select hierarchical data?

I have a table in SQL Server that is structured like this:

id  Name  Parent
--  ----  ------
1   foo   null
2   bar   1
3   oof   null
4   rab   3
.
.
.

I need to get the data from the two associated rows as one row in a .NET DataTable . My desired DataTable would look like this:

Parent  Child
------  -----
foo     bar
oof     rab

I was able to accomplish this using the query below:

with temp as
(
  SELECT 1 id,'foo' name, null parent
  UNION
  select 2,'bar', 1
  UNION
  SELECT 3,'oof', null
  UNION
  select 4,'rab', 3
)

SELECT t1.name parent, t2.name child
FROM temp t1
INNER JOIN temp t2
ON t1.id = t2.parent

But I am curious if there is an easy way to do this using LINQ? (our shop uses LINQ for most database access)

Upvotes: 3

Views: 2617

Answers (4)

Doggett
Doggett

Reputation: 3464

I prefer to keep the joins as joins

var result = from t1 in table
join t2 in table on t1.id = t2.parent
select new { parent = t1.name, child = t2.name }

Upvotes: 2

jasper
jasper

Reputation: 3474

var result = source.Select(child => new { 
 Child = child, 
 Parent = source.SingleOrDefault(parent => parent.ID == child.Parent)
});

Upvotes: 0

Jake Kalstad
Jake Kalstad

Reputation: 2065

data.Select(d => d.Parent).Select(p => p.Property).ToList();

select will just project the results back to you lazy loaded. So simple select what you need into either a local list, or with a little syntax you can use the anonymous projection to bottle all the levels of data together and filter on that before .ToList()'ing back to ya.

Upvotes: 0

Dustin Laine
Dustin Laine

Reputation: 38543

DataTable dt = new DataTable()
//Other DT stufff

//LINQ Query
var data = from t in table
           select t;

//Loop to create DT
foreach (item in data.ToList())
{
    DataRow dr = new DataRow();
    dr["Parent"] = item.Name;
    dr["Child"] = item.item.Name; //Where item.item is your FK relation to itself
    dt.Rows.Add(dr);
}

Upvotes: 1

Related Questions