如何使用linq为类别和子类别创建面包屑

时间:2014-02-06 15:55:43

标签: asp.net linq

如何为父级使用其parentid列指定的无限子类别的类别创建面包屑?

想象一下以下表格条目:

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

1 个答案:

答案 0 :(得分:1)

如果处理完整集的递归函数正常,则以下内容应该有效。 我把它扔在LINQPad中。神奇的是递归函数GetBreadcrumbs。我在小狗下添加了第三级“拳击手”。

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; }
}