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

.net Linq to SQL:选择没有子类别的类别,.net,linq-to-sql,.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字段中使用的所有类别,但我不知道如何编写它。尝试以下方法: from c in model.Categories where !(from inn

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

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字段中使用的所有类别,但我不知道如何编写它。

尝试以下方法:

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)
尝试:

List GetChildlessCategories()
{
列出ParentId=context.Categories.Select(x=>x.ParentId);
返回context.Categories.Where(c=>!parentsIds.Contains(c.CategoryId));
}
在平面表上工作更容易,因为可以将其加载到关系结构中,并尝试再次处理每个节点,然后重新处理整个(平面)结构

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