LINQ2SQL:orderby note.hasChildren(),名称升序

时间:2010-05-25 09:11:48

标签: sql linq linq-to-sql treeview hierarchical-data

我有分层数据结构,我在网页中显示为树视图。

我希望将数据排序为首先显示按字母顺序排列的节点,这些节点没有子节点,然后在这些节点下按字母顺序排序,这些节点有子节点。 目前我正在订购一个组中的所有节点,这意味着带有子节点的节点出现在没有子节点的节点旁边。

我正在使用递归方法来构建树视图,它的核心是LINQ代码:

    var filteredCategory = from c in category
                           orderby c.Name ascending
                           where c.ParentCategoryId == parentCategoryId && c.Active == true
                           select c;

所以这是我想要增强的orderby语句。

下面显示的是数据库表结构:

[dbo].[Category](
    [CategoryId] [int] IDENTITY(1,1) NOT NULL,
    [Name] [varchar](100) NOT NULL,
    [Level] [tinyint] NOT NULL,
    [ParentCategoryId] [int] NOT NULL,
    [Selectable] [bit] NOT NULL CONSTRAINT [DF_Category_Selectable]  DEFAULT ((1)),
    [Active] [bit] NOT NULL CONSTRAINT [DF_Category_Active]  DEFAULT ((1))

3 个答案:

答案 0 :(得分:0)

试试这个(替换c.Category)与孩子IQueryable<>:

var filteredCategory = from c in category 
       orderby c.Category.Count == 0
       where c.ParentCategoryId == parentCategoryId && c.Active == true 
       select c; 

答案 1 :(得分:0)

如果你正在使用Linq2SQL,你不能只通过获取没有父项的所有类别来构建树,然后根据需要访问子项来构建树吗?

我的意思是像这个查询一样选择根类别:

Category[] rootCats = (from c in category
    orderby c.Name ascending
    where c.ParentCategoryId == 0 // that is, no parent = root element
        && c.Active == true
    select c).ToArray();

然后通过IEnumerable<Category>访问指定类别(oneCat.Category.Where( cat => cat.Active == true))的子项。

答案 2 :(得分:0)

var filteredCategory = category
  .Where(c => c.ParentCategoryId == parentCategoryId
    && c.Active == true)
  .OrderBy(c => c.Children.Any() ? 1 : 2)
  .ThenBy(c => c.Name);

如果您没有Children属性,请转到linq to sql designer并创建一个添加该属性的关联。

相关问题