Преобразование дерева в узел списка с путями от корня к листу .NET C#C#

Место общения программистов C#
Ответить Пред. темаСлед. тема
Гость
 Преобразование дерева в узел списка с путями от корня к листу .NET C#

Сообщение Гость »


I have a n-ary tree structure that has nodes with children. Each node is a "folder" and folders can have child folders (i.e. nested folder) or simply a file (leaf node). I want to convert this structure to a list of folders where each folder name is a composite root to last folder and contains the all the leaf nodes in that last folder. So, for example:
  • Root Folder1 File1
  • File2
[*]Folder2
  • Folder3 File3
[*]File 4
Would result in a List with Folder/File members
  • Folder1 - File1, File2
  • Folder2.Folder3 - File3
  • Folder2 - File4

Sample code/setup:

public interface INode { } public class Folder : INode { public string Name { get; set; } public List? Children { get; set; } } public class File : INode { public string Name { get; set; } } var tree = new Folder() { Name = "Root" }; var folder1 = new Folder() { Name = "Folder1" }; var file1 = new TreeConverter.File() { Name = "File1" }; var file2 = new TreeConverter.File() { Name = "File2" }; folder1.Children = new List { file1, file2 }; var folder2 = new Folder() { Name = "Folder2" }; var folder3 = new Folder() { Name = "Folder3" }; var file3 = new TreeConverter.File() { Name = "File3" }; var file4 = new TreeConverter.File() { Name = "File4" }; folder3.Children = new List { file3 }; folder2.Children = new List() { folder3, file4 }; tree.Children = new List() { folder1, folder2 }; List folders = ConvertTreeToListofFoldersWithEachEntryNamedRootToLastFolderWithAllContainingFileNodes(tree); // folders would contain folders named as such: [Folder1, Folder2.Folder3, Folder2] // which one could iterate over the children of each node to get the leaf nodes. Thank you.

Ps: This is a variation of Printing all the paths in a tree from root to each leaf I think. Just the output is not a print but another data structure.


Источник: https://stackoverflow.com/questions/781 ... et-c-sharp
Реклама
Ответить Пред. темаСлед. тема

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

  • Похожие темы
    Ответы
    Просмотры
    Последнее сообщение

Вернуться в «C#»