构建目录结构

时间:2018-06-06 09:56:35

标签: c# recursion

我的情况是我得到一个表示目录结构的List,格式如下:

"My Folder\Images"
"My Folder\Images\Gif"
"My Folder\Images\JPG"
"My Folder\Media"
"My Folder\Media\Mov"
"My Folder\Media\Mov\QT"
"My Folder\Media\MPG"

对于可以嵌套多少级别没有限制。

我需要构建一个代表树视图的东西,格式为:

public class Folder
{
    public string FolderName { get; set; }
    public List<Folder> Folders{ get; set; } // a list of subfolders
}

我无法获得构建此功能的recrusive功能。非常感谢大师的任何帮助。

TIA

编辑:我的完整课程定义是:

public class Folder
{
    public string Name { get; set; }

    public List<Folder> Folders { get; set; }
    public Folder(List<string> input)
    {
        foreach (var folder in input)
        {
            var delimPos = folder.IndexOf("\\");
            if (delimPos == -1)
            {
                Name = folder ;
            }
            else
            {
                Name = folder.Substring(0, delimPos);
                var subFolders= input.Select(o => o.Substring(delimPos + 1)).ToList();
                Folders= new List<Folder>();
                foreach (var subFolder in subFolders)
                {
                    Folders.Add(new Folder(new List<string>() { subFolder }));
                }

            }
        }
    }
}

3 个答案:

答案 0 :(得分:2)

您当然遇到的问题是,在拆分和处理Images\Gif之后,您将在拆分和处理Images时重新添加另一个Images\JPG文件夹。第一个将有一个Gif子文件夹,第二个将有一个JPG子文件夹。

您可以通过对第一部分进行分组来解决此问题,并且只处理后面的部分:

public static List<Folder> ParseInputRecursive(string[] input)
{
    var foldersInParts = input.Select(f => f.Split(new [] { '\\' }, StringSplitOptions.RemoveEmptyEntries).ToList()).ToList();

    return ParseInputRecursive(foldersInParts);
}

public static List<Folder> ParseInputRecursive(List<List<string>> input)
{
    var folders = new List<Folder>();

    foreach (var folderPartsGroup in input.GroupBy(p => p[0]))
    {
        var folder = new Folder { Name = folderPartsGroup.Key };

        // Remove parent name, skip parent itself
        var subFolders = folderPartsGroup.Select(f => f.Skip(1).ToList()).Where(f => f.Count > 0).ToList();

        folder.Folders = ParseInputRecursive(subFolders);

        folders.Add(folder);
    }

    return folders;
}

打印它们以验证:

// Sort to make sure parents always come first
Array.Sort(input);
var rootFolders = ParseInputRecursive(input);

foreach (var folder in rootFolders)
{
    PrintFoldersRecursive(folder);
}

public static void PrintFoldersRecursive(Folder folder, int depth = 0)
{
    Console.WriteLine(new string('*', depth++) + folder.Name);

    foreach (var subFolder in folder.Folders)
    {
        PrintFoldersRecursive(subFolder, depth);
    }
}

鉴于此输入:

var input = new string[] 
{
    @"F1\Images",
    @"F1\Images\Gif",
    @"F1\Images\JPG",
    @"F1\Media",
    @"F1\Media\Mov",
    @"F2\Docs",
    @"F2\Docs\Foo",
};

给出这个输出:

F1
*Images
**Gif
**JPG
*Media
**Mov
F2
*Docs
**Foo

答案 1 :(得分:0)

对于通过字符串解析进行的简单节点遍历,请参阅以下示例

private void button1_Click(object sender, EventArgs e)
        {
            var folders = ProcessNode("My Folder\\Media\\Mov\\QT", 0);
            MessageBox.Show("finished");

        }
        private Folder ProcessNode(string input, int index)
        {
            var newIndex = input.IndexOf("\\", index + 1);
            if (newIndex < 0) return new Folder() { FolderName = input.Substring(index, input.Length - index) };
            var nodeName = input.Substring(index, newIndex - index);
            var thisFolder = new Folder()
            {
                FolderName = nodeName,
                Folders = new List<Folder>()
            };
            thisFolder.Folders.Add(ProcessNode(input, newIndex));
            return thisFolder;
        }

如果要使用拆分功能和列表

    private void button1_Click(object sender, EventArgs e)
        {

            var splitted = "My Folder\\Media\\Mov\\QT".Split('\\').ToList();
            var foldersList = ProcessNode(splitted, 0);
            MessageBox.Show("finished");

        }     
private Folder ProcessNode(List<string> input, int index)
            {
                if (index >= input.Count) return null;
                var thisFolder = new Folder()
                {
                    FolderName = input[index],
                    Folders = new List<Folder>()
                };
                thisFolder.Folders.Add(ProcessNode(input, index + 1));
                return thisFolder;
            }

答案 2 :(得分:0)

下面是一个非递归解决方案,它根据需要解析并打印值。如果有帮助,请告诉我。 Demo

逻辑

        public static IEnumerable<Folder> Parse(IEnumerable<string> locations)
        {
            var folders = new List<Folder>();
            foreach (var location in locations)
            {
                var parts = location.Split(new[]{Path.DirectorySeparatorChar}, StringSplitOptions.RemoveEmptyEntries);
                Folder currentFolder = null;
                foreach (var part in parts)
                {
                    var parentFolders = currentFolder!=null ? currentFolder.Folders : folders;
                    currentFolder = parentFolders.Find(folder => folder.Name == part) ?? new Folder { Name = part };
                    if (!parentFolders.Any(folder => folder.Name.Equals(currentFolder.Name)))
                    {
                        parentFolders.Add(currentFolder);
                    }
                }
            }
            return folders;
        }

完整计划

//Rextester.Program.Main is the entry point for your code. Don't change it.
//Compiler version 4.0.30319.17929 for Microsoft (R) .NET Framework 4.5
using System;
using System.IO;
using System.Linq;
using System.Collections.Generic;
namespace Rextester
{

    public class Folder
    {
        public string Name { get; set; }

        public List<Folder> Folders { get; internal set; }

        public Folder()
        {
            this.Folders = new List<Folder>();
        }

       public static IEnumerable<Folder> Parse(IEnumerable<string> locations)
        {
            var folders = new List<Folder>();
            foreach (var location in locations)
            {
                var parts = location.Split(new[]{Path.DirectorySeparatorChar}, StringSplitOptions.RemoveEmptyEntries);
                Folder currentFolder = null;
                foreach (var part in parts)
                {
                    var parentFolders = currentFolder!=null ? currentFolder.Folders : folders;
                    currentFolder = parentFolders.Find(folder => folder.Name == part) ?? new Folder { Name = part };
                    if (!parentFolders.Any(folder => folder.Name.Equals(currentFolder.Name)))
                    {
                        parentFolders.Add(currentFolder);
                    }
                }
            }
            return folders;
        }

        public override string ToString()
        {
            if (this.Folders.Count == 0)
            {
                return this.Name;
            }
            else
            {
                var folders = this.Folders
                    .SelectMany(folder => folder.ToString().Split(new[] { Environment.NewLine }, StringSplitOptions.None))
                    .Select(f => this.Name + Path.DirectorySeparatorChar + f);
                return string.Join(Environment.NewLine, folders);
            }

        }
    }

    public class Program
    {
        public static void Main(string[] args)
        {
            var locationList = new List<string>()
                                   {
                                       @"My Folder\Images",
                                       @"My Folder\Media",
                                       @"My Folder\Images\Gif",
                                       @"My Folder\Images\JPG",
                                       @"My Folder\Media\Mov",
                                       @"My Folder\Media\Mov\QT",
                                       @"My Folder\Media\MPG"
                                   };
            var folderLists = Folder.Parse(locationList);
            Console.WriteLine(string.Join(Environment.NewLine, folderLists));
            Console.ReadLine();
        }
    }
}

输出:

My Folder\Images\Gif
My Folder\Images\JPG
My Folder\Media\Mov\QT
My Folder\Media\MPG