Linq to SQL:选择没有子类别的类别

时间:2009-09-01 03:06:08

标签: .net linq-to-sql

我需要抓住所有没有子类别的类别

1
^--1.1
^--1.2
    ^--1.2.3

2
^--2.1

3

在这个例子中,我想得到[1.1],[1.2.3],[2.1]和[3]。

我的类别表如下所示:

CategoryID | CategoryName | ParentID 

我想我应该选择所有类别,其中CategoryID没有用于任何其他类别的ParentID字段,但我对如何编写它感到茫然。

2 个答案:

答案 0 :(得分:3)

试试这个:

from c in model.Categories
where !(from inner_c in model.Categories
        select inner_c.ParentID).Contains(c.CategoryID)
select c

子查询是关键 - 我们试图转换为LINQ:

SELECT * FROM categories WHERE categoryID NOT IN (SELECT parentID FROM categories)

答案 1 :(得分:0)

尝试:

List<Category> GetChildlessCategories()
{
    List<int> parentIds = context.Categories.Select(x => x.ParentId);
    return context.Categories.Where(c => !parentsIds.Contains(c.CategoryId));
}

更容易在平台上工作,将其加载到关系结构,并尝试再次处理整个(平面)结构的每个节点。