开发者

Using LINQ to select hierarchical data?

开发者 https://www.devze.com 2023-01-23 05:39 出处:网络
I have a table in SQL Server that is structured like this: idNameParent ------------ 1foonull 2bar1 3oofnull

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 assoc开发者_如何学运维iated 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)


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 }


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);
}


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.


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

精彩评论

暂无评论...
验证码 换一张
取 消