使用LINQ创建类似层次结构的面包屑

时间:2011-09-18 09:18:04

标签: c# .net linq linq-to-entities breadcrumbs

我正在构建一个类似Dropbox的应用程序来存储图像。

我有一个名为Images的数据库表:

ImageId [PK]
ParentImageId [FK]
Name
Path

我想从上面的结构创建一个面包屑,假设我有以下数据:

enter image description here

是否可以使用LINQ创建一个看起来像的痕迹(如果我在子文件夹2中) :

Folder 1 > Sub Folder 1 > Sub Folder 2

如何构建查询以返回所需的结果?任何帮助都会有很大的帮助!

2 个答案:

答案 0 :(得分:5)

使用Entity Framework,您可以执行下一步:

enter image description here

代码看起来像这样:

var image = db.Images.FirstOrDefault(i => i.Id == currImageId);

var imagesHierarchy = new List<Image>();
if (image != null)
{
    var parent = image.Parent;
    while (parent != null)
    {
        imagesHierarchy.Insert(0, parent);
        parent = parent.Parent;
    }
}

var breadcrumb = string.Join(" > ", imagesHierarchy.Select(i => i.Name));

答案 1 :(得分:1)

这样做:

var current = new Record
    { ImageId = 4, ParentImageId = 3, Name = "Sub Folder 2" };

var records = new []
{
    new Record { ImageId = 1, ParentImageId = 1, Name = "Folder 1" },
    new Record { ImageId = 2, ParentImageId = 1, Name = "Image 1" },
    new Record { ImageId = 3, ParentImageId = 1, Name = "Sub Folder 1" },
    current,
    new Record { ImageId = 5, ParentImageId = 4, Name = "Sub Image" },
};

var index = records.ToDictionary(r => r.ImageId);

Func<Record, IEnumerable<Record>> traverseUp = null;
traverseUp = r =>
{
    var rs = new [] { r, };
    if (r.ParentImageId == r.ImageId)
    {
        return rs;
    }
    else
    {
        return traverseUp(index[r.ParentImageId]).Concat(rs);
    }
};

var breadcrumb = String.Join(" > ", traverseUp(current).Select(r => r.Name));