2010-11-01 59 views
3

我在SQL Server中的表的结构是这样的:使用LINQ选择分层数据?

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

我需要从两个相关联行的数据作为一个行中的.NET数据表。我想要的数据表是这样的:

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

我可以使用下面的查询来实现:

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 

不过我很好奇,如果有一个简单的方法来做到这一点使用LINQ? (本店使用LINQ对于大多数数据库访问)

回答

1
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); 
} 
+0

你的LINQ语句这里是一个无操作...为什么不使用LINQ加入? – 2012-03-16 17:26:05

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

选择只会项目结果反馈给你延迟加载。简单地选择你需要的东西到本地列表中,或者使用一点语法,你可以使用匿名投影将所有数据级别集中在一起,并在之前过滤.ToList()返回到ya。

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

我宁愿保持连接为连接

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