平面列表到层次结构 [英] flat list to hierarchy

查看:72
本文介绍了平面列表到层次结构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最难将列表(文件夹)转换为层次结构.

I'm having the hardest time converting a list(Of Folder) into a hierarchy.

Public Class Folder

Public Property FolderID() As Integer
Public Property Name() As String
Public Property ParentFolderID() As Integer
Public Property Children() as IEnumerable(Of Folder)

End Class

我需要返回填充了子代的List(文件夹).

I need to return List(Of Folder) with Children populated.

我从数据库中的数据构建一个List(文件夹).

I build a List(Of Folder) from the data in the database.

{1,文件夹1",什么都没有} {2,文件夹2",1} {3,文件夹3",2} {4,文件夹4",3} {5,文件夹5",什么都没有}

{1, "Folder 1", Nothing} {2, "Folder 2", 1} {3, "Folder 3", 2} {4, "Folder 4", 3} {5, "Folder 5", Nothing}

我不知道如何将子文件夹递归移动到其父文件夹的Children属性中.

I can't figure out how to recursively move the child folders into the Children property of their parent.

我想用LINQ做到这一点.

I would like to do this with LINQ.

非常感谢您的帮助.

更新

谢谢您的回答,但还不够.根据您的回答,我提出了几乎可行的解决方案.

Thank you for your answer, but not quite there. Based on your answer, I came up with this which almost works.

Dim list = (From folder in folderList Select New Folder() With {
    .FolderID = folder.FolderID, 
    .Name = folder.Name, 
    .ParentFolderID = folder.ParentFolderID, 
    .Children = (From child in folderList 
                 Where child.ParentFolderID = item.FolderID).ToList()}).ToList()

{1, "Root", Nothing}
{2, "Child", 1}
{3, "Grand Child", 2}

我会得到所有三个文件夹的列表:

I get a list of all three folders:

Root
--Child
Child
--Grand Child
Grand Child

应该像这样:

Root
--Child
----Grand Child

推荐答案

如果使用ToLookup扩展方法,则很容易.

It's easy if you use the ToLookup extension method.

C#:

var lookup = folderList.ToLookup(f => f.ParentFolderID);

foreach (var folder in folderList)
{
    folder.Children = lookup[folder.FolderID].ToList();
}

var rootFolders = lookup[null].ToList();

VB:

Dim lookup = folderList.ToLookup(Function (f) f.ParentFolderID)

For Each folder In folderList
    folder.Children = lookup(folder.FolderID).ToList()
Next

Dim rootFolders = lookup(Nothing).ToList()

这篇关于平面列表到层次结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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