LINQ to SQL-按parentId分组类别 [英] LINQ to SQL - Grouping categories by parentId

查看:102
本文介绍了LINQ to SQL-按parentId分组类别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用数据库中的Categories表构造导航菜单.

I am trying to construct a navigation menu using a Categories table from my db.

我在类别"表中的布局与下面类似.

I have a similar layout as below in Categories table.

public List<Category> CategoryData = new List(new Category[] {  
                                        new Category{ CategoryId = 1, Name = "Fruit", ParentCategoryId = null},
                                        new Category{ CategoryId = 2, Name = "Vegetables", ParentCategoryId = null},
                                        new Category{ CategoryId = 3, Name = "Apples", ParentCategoryId = 1},
                                        new Category{ CategoryId = 4, Name = "Bananas", ParentCategoryId = 1},
                                        new Category{ CategoryId = 5, Name = "Cucumber", ParentCategoryId = 2},
                                        new Category{ CategoryId = 6, Name = "Onions", ParentCategoryId = 2}
                                );  }

上面的代码应该返回类似的内容

The above should return something like

水果(父母)

 "===Apples, Bananas (child)

蔬菜(父母)

"===Cucumber, Onions (child)

我需要能够将其作为某种分组"(按父母身份分组)集合传递给我的视图.

I need to be able to pass this as some kind of 'grouped' (grouped by parentid) collection to my View.

如何执行此操作?

推荐答案

这似乎是将模型转换为viewModel的一个好例子.您可以使用@thomas描述的相同技术创建具有CategoryViewModel的Childrens属性的CategoryViewModel的集合.

It would seem like this is a good example of when translating your model to a viewModel would come in handy. As you could create a collection of CategoryViewModel which have a Childrens property of CategoryViewModel using the same technique describe by @thomas.

public class CategoryViewModel
{
     public int CategoryId { set; get; }
     public string CategoryName { set; get; }
     public int? ParentCategoryId { set; get; }
     public IEnumerable<CategoryViewModel> Children { set; set; }
}

public static IEnumerable<CategoryViewModel> GetAllCategoryViewModel(IList<Category> categories) 
{
      var query = GetChildren(null, categories);
      return query.ToList();

}

public static IEnumerable<CategoryViewModel> GetChildren(int? parentId, IList<Category> categories)
{
     var children = from category in categories
                    where category.ParentCategoryId == parentId
                    select  
                     new CategoryViewModel
                     {
                       CategoryId = category.CategoryId,
                       CategoryName = category.CategoryName,
                       ParentCategoryId = category.ParentCategoryId,
                       Children = GetChildren(category.CategoryId, categories)
                     };

     return children;
}

这篇关于LINQ to SQL-按parentId分组类别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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