2010-11-01 54 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 }