我最困难的时间将列表(文件夹)转换为层次结构。

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(文件夹)。

我从数据库中的数据构建一个列表(文件夹)。

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

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

我想用LINQ做到这一点。

任何帮助是极大的赞赏。

更新

谢谢您的回答,但还不够。根据您的回答,我提出了几乎可行的解决方案。
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}

我得到所有三个文件夹的列表:
Root
--Child
Child
--Grand Child
Grand Child

应该看起来像:
Root
--Child
----Grand Child

最佳答案

如果使用ToLookup扩展方法,这很容易。

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()

关于linq - 平面列表到层次结构,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/4694227/

10-14 13:53
查看更多