c# - Linq 在嵌套集模型中获取直接子级

标签 c# sql linq nested-sets

Nested Set Model ,将 sql 转换为 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 来表达它,所以我跪下向你学习。

最佳答案

这有效(注意不同的在 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();

关于c# - Linq 在嵌套集模型中获取直接子级,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25592970/

相关文章:

c# - 使用 LINQ 分页而不排序

c# - 系统.ArgumentNullException : Value cannot be null in unit test - C#

c# - 如何防止插件执行有害代码

c# - 参数化 LINQ GroupBy

sql - 为什么在Sql中不能使用Plsql包变量和常量?

sql - 在 SQL 或 Django ORM 中,订购一对多的常规方法是什么?

c# - 用户定义的过滤器/查询?

c# - 怀疑在 IAppBuilder.CreatePerOwinContext() 中注册的对象是否会被处置

c# - DLR LambdaExpressions 和 System.Runtime.CompilerServices.Closure 对象

java - 使用 Java、SQL 和 Oracle 引用和引用表的 List 或 ArrayList