Linq让嵌套组合模型中的直系孩子 [英] Linq to get immediate children in Nested Set Model

查看:51
本文介绍了Linq让嵌套组合模型中的直系孩子的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嵌套集模型中,将sql转换为linq对我来说是一个挑战.

In Nested Set Model, there's a challenge for me to convert sql to linq.

上面的Wikipedia链接显示了如何按照sql语法下面列出给定节点的直接子级,并且当我使用LinqPad对其进行测试时,效果很好.

The above wikipedia link shows how to list up immediate children of given node as below sql syntax, and it works well when I test it with 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来表达它,所以我屈膝向你学习.

I'm stuck with expressing it with LINQ, so I'm on my knees to learn from you.

推荐答案

这有效(请注意,在SQL中,区别是多余的):

This works (note the distinct is superfluous in the 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的完整示例:

Full sample for 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();

这篇关于Linq让嵌套组合模型中的直系孩子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆