2014-08-31 27 views
2

Nested Set Model中,將sql轉換爲linq存在一個挑戰。Linq在嵌套集模型中獲得直接的孩子

上面的維基百科鏈接顯示瞭如何列出給定節點的直接子節點,如下面的sql語法,並且當我使用LinqPad進行測試時,它運行良好。

SELECT DISTINCT Child.Name 
FROM ModelTable AS Child, ModelTable AS Parent 
WHERE Parent.Lft < Child.Lft AND Parent.Rgt > Child.Rgt -- associate Child Nodes with ancestors 
GROUP BY Child.Name 
HAVING MAX(Parent.Lft) = 16 -- Subset for those with the given Parent Node as the nearest ancestor 

我一直用LINQ表達它,所以我跪在地上向你學習。

回答

3

這工作(注意,不同的是多餘的SQL):

from c in nodes 
from p in nodes 
where c.Left > p.Left && c.Right < p.Right 
group p by c into g 
where g.Max(x => x.Left) == 1 
select g.Key; 

爲linqpad全樣本:

var nodes = new [] { new {Name = "Clothing", Left = 1, Right = 22} }.ToList(); 

nodes.Add(new {Name = "Clothing", Left = 1, Right = 22}); 
nodes.Add(new {Name = "Men's", Left = 2, Right = 9}); 
nodes.Add(new {Name = "Women's", Left = 10, Right = 21}); 
nodes.Add(new {Name = "Suits", Left = 3, Right = 8}); 
nodes.Add(new {Name = "Slacks", Left = 4, Right = 5}); 
nodes.Add(new {Name = "Jackets", Left = 6, Right = 7}); 
nodes.Add(new {Name = "Dresses", Left = 11, Right = 16}); 
nodes.Add(new {Name = "Skirts", Left = 17, Right = 18}); 
nodes.Add(new {Name = "Blouses", Left = 19, Right = 20}); 
nodes.Add(new {Name = "Evening Gowns", Left = 12, Right = 13}); 
nodes.Add(new {Name = "Sun Dresses", Left = 14, Right = 15}); 

var q = 
    from c in nodes 
    from p in nodes 
    where c.Left > p.Left && c.Right < p.Right 
    group p by c into g 
    where g.Max(x => x.Left) == 1 
    select g.Key; 

q.Dump(); 
+1

哇。你是linq的絕地大師!謝謝。 – Youngjae 2014-09-01 00:42:04