gpt4 book ai didi

c# - 帮助编写文件夹结构的算法

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:32:58 25 4
gpt4 key购买 nike

我正在使用 MongoDB,我需要编写一个算法来填充以下类,以构建树状目录结构:

public class Dir 
{
public string name { get; set; }
public string hash { get; set; }
public bool read { get; set; }
public bool write { get; set; }
public Dir[] dirs { get; set; }
}

我将从 MongoDB 中获取这样的文件夹列表字符串,不同且已排序(空字符串是根):

 Folder1
Folder2
Folder2/ChildFolder
Folder2/ChildFolder2
Folder2/ChildFolder3
Folder2/ChildFolder3/Folderrrr
Folder2/ChildFolder3/Hi
""

我应该有一个 Dir 对象,它是根文件夹,在那个里面我应该有一个目录数组,在每个目录上我可以有另一个目录数组等等......

有什么想法吗?感谢您的帮助

最佳答案

适用于您的示例数据,但将来可能需要进行一些更新

    static void Main(string[] args)
{
var folders = new[] { "Folder1","Folder2","Folder2/ChildFolder","Folder2/ChildFolder2","Folder2/ChildFolder3",
"Folder2/ChildFolder3/Folderrrr", "Folder2/ChildFolder3/Hi"
};
var root = new Dir("Root");
foreach (var folder in folders)
{
BuildTree(folder, root);
}
}

private static void BuildTree(string path, Dir parent)
{
if (parent == null) return;

if (path.Contains("/"))
{
var dir = path.Substring(0, path.IndexOf("/"));
var newPath = path.Substring(dir.Length + 1);
Dir addNodeTo;
if (!parent.Contains(dir))
{
var newParent = new Dir(dir);
parent.Dirs.Add(newParent);
addNodeTo = newParent;
}
else
{
addNodeTo = parent.Get(dir);
}
BuildTree(newPath, addNodeTo);
}
else
{
if (!parent.Contains(path))
parent.Dirs.Add(new Dir(path));
}
}

public class Dir
{
public string Name { get; private set; }
public string Hash { get; set; }
public bool Read { get; set; }
public bool Write { get; set; }
public List<Dir> Dirs { get; private set; }

public Dir(string name)
{
Name = name;
Dirs = new List<Dir>();
}

public bool Contains(string name)
{
return Dirs.Any(d => d.Name.Equals(name));
}

public Dir Get(string name)
{
return Dirs.FirstOrDefault(d => d.Name.Equals(name));
}

public override string ToString()
{
return Name;
}
}

关于c# - 帮助编写文件夹结构的算法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7433414/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com