Using LINQ to select hierarchical data?

I have a table in SQL Server that is structured as follows:

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

I need to get data from two related 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 following query:

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'm curious if there is an easy way to do this using LINQ? (our store uses LINQ for most database access)

+3
source share
4 answers
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);
}
+1
source

I prefer to save 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 }
+2
source
data.Select(d => d.Parent).Select(p => p.Property).ToList();

select . , , , , , .ToList() ya.

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

Source: https://habr.com/ru/post/1772566/


All Articles