gpt4 book ai didi

c# - 层次结构路径列表

转载 作者:行者123 更新时间:2023-12-02 00:56:09 25 4
gpt4 key购买 nike

我有一个这样的路径列表:

Root 
Root/Folder1
Root/Folder1/SubFolder1.1
Root/Folder1/SubFolder1.2
Root/Folder2
OtherRootFolder
OtherRootFolder/Folder1

我需要使用文件夹 + 子列表创建层次结构

public class FolderTreeModel
{
public string Title { get; set; }
public List<FolderTreeModel> Children { get; set; }
}

如何将该路径拆分为该结构以使其看起来像:

Root
'-- Folder1
'---- SubFolder1.1
'---- SubFolder1.2
'-- Folder2
'-- OtherRootFolder
'---- Folder1

提前致谢。

最佳答案

这是您需要的代码:

Action<FolderTreeModel, IEnumerable<string>> ensureExists = null;
ensureExists = (ftm, ts) =>
{
if (ts.Any())
{
var title = ts.First();
var child = ftm.Children.Where(x => x.Title == title).SingleOrDefault();
if (child == null)
{
child = new FolderTreeModel()
{
Title = title,
Children = new List<FolderTreeModel>(),
};
ftm.Children.Add(child);
}
ensureExists(child, ts.Skip(1));
}
};

然后我可以这样做:

var paths = new []
{
"Root",
"Root/Folder1",
"Root/Folder1/SubFolder1.1",
"Root/Folder1/SubFolder1.2",
"Root/Folder2",
"OtherRootFolder",
"OtherRootFolder/Folder1",
};

var root = new FolderTreeModel() { Title = "/", Children = new List<FolderTreeModel>() };

foreach (var path in paths)
{
var parts = path.Split('/');
ensureExists(root, parts);
}

然后我得到这个结果:

result

如果将 FolderTreeModel 的定义更改为:

public class FolderTreeModel : List<FolderTreeModel>
{
public string Title { get; set; }
}

...然后代码变得更简单一些:

Action<FolderTreeModel, IEnumerable<string>> ensureExists = null;
ensureExists = (ftm, ts) =>
{
if (ts.Any())
{
var title = ts.First();
var child = ftm.Where(x => x.Title == title).SingleOrDefault();
if (child == null)
{
child = new FolderTreeModel() { Title = title };
ftm.Add(child);
}
ensureExists(child, ts.Skip(1));
}
};

var root = new FolderTreeModel() { Title = "/" };

其余代码相同。

关于c# - 层次结构路径列表<string>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34947623/

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