如何使用linq为类别和子类别创建面包屑 [英] How to create a breadcrumb for categories and subcategories using linq

查看:51
本文介绍了如何使用linq为类别和子类别创建面包屑的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何为父项在其parentid列中指定的子类别不受限制的类别创建面包屑?

How to create breadcumb for categories with unlimited subcategories which their parent specified with their parentid column?

想象一下下表中的条目:

Imagine the following table entries:

id    name      parentid
=========================
1     animal    NULL
2     veg       NULL
3     mineral   NULL
4     doggie    1
5     kittie    1
6     horsie    1
7     gerbil    1
8     birdie    1
9     carrot    2
10    tomato    2
11    potato    2
12    celery    2

推荐答案

如果可以在整个集合上使用递归函数,则可以使用以下函数. 我把它放在LINQPad中.魔术是递归函数GetBreadcrumbs.我在小狗"下添加了第三级拳击手".

If a recursive function working on the full set is ok then the following should work. I threw it together in LINQPad. The magic is the recursive function GetBreadcrumbs. I added a third level "boxer" under doggie.

void Main()
{
    var list = new List<MyEntity>()
    {
        new MyEntity() { Id = 1, Name = "animal" },
        new MyEntity() { Id = 2, Name = "veg" },
        new MyEntity() { Id = 3, Name = "mineral" },
        new MyEntity() { Id = 4, Name = "doggie", ParentId = 1 },
        new MyEntity() { Id = 5, Name = "kittie", ParentId = 1 },
        new MyEntity() { Id = 6, Name = "horsie", ParentId = 1 },
        new MyEntity() { Id = 7, Name = "gerbil", ParentId = 1 },
        new MyEntity() { Id = 8, Name = "birdie", ParentId = 1 },
        new MyEntity() { Id = 9, Name = "carrot", ParentId = 2 },
        new MyEntity() { Id = 10, Name = "tomato", ParentId = 2 },
        new MyEntity() { Id = 11, Name = "potato", ParentId = 2 },
        new MyEntity() { Id = 12, Name = "celery", ParentId = 2 },
        new MyEntity() { Id = 13, Name = "boxer", ParentId = 4 },
    };

    var breadcrumbs = GetBreadcrumbs(list); 
    foreach (var breadcrumb in breadcrumbs)
        Console.WriteLine(breadcrumb);

}

// This is where the Magic happens!
public IEnumerable<string> GetBreadcrumbs(IEnumerable<MyEntity> entities, int? parentId = null)
{
    var parents = entities.Where(x => x.ParentId == parentId);
    var children = entities.Where(x => x.ParentId != parentId);

    foreach (var parent in parents)
    {
        yield return parent.Name;
        foreach (var trail in GetBreadcrumbs(children, parent.Id))
            yield return (parent.Name + " > " + trail);
    }
}

public class MyEntity
{
    public int Id { get; set; }
    public string Name { get; set; }
    public int? ParentId { get; set; }
}

这篇关于如何使用linq为类别和子类别创建面包屑的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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