需要帮助搜索嵌套列表C#



我需要实现Search函数,这样它就会输出搜索到的"文件夹";。

{
public class Folder
{
public string root { get; set; }
public List<Folder> children { get; set; }
}
static void Main(string[] args)
{
string searchString = "sub-folder3"; //Folder to be searched
//Test input
Folder input = new Folder
{
root = "folder",
children = new List<Folder>
{
new Folder
{
root = "sub-folder",
children = new List<Folder>()
},
new Folder
{
root = "sub-folder2",
children = new List<Folder>
{
new Folder
{
root = "sub-folder31",
children = new List<Folder>()
},
new Folder
{
root ="sub-folder3",
children = new List<Folder>()
}
}
},
new Folder
{
root ="sub-folder4",
children = new List<Folder>()
{
new Folder
{
root = "sub-sub-folder4",
children = new List<Folder>()
}
}
},
new Folder
{
root ="useless",
children = new List<Folder>()
}
}
};
List<string> paths = Search(input, searchString);
foreach (var path in paths)
Console.WriteLine(path);
}

/// <summary>
/// Returns array of full paths to searched folder
/// </summary>
/// <param name="input"></param>
/// <param name="searchString"></param>
/// <returns></returns>
private static List<string> Search(Folder input, string searchString)
{
throw new NotImplementedException("Complete this function. You can add or remove arguments as you see fit, but function must return array of full paths to the searched folder (or folders)");

如果我正确理解这一点,您希望获得与给定目录的某些搜索条件匹配的所有子目录,并将完整路径放在列表中。这可以使用递归实现,如下所示:

public static List<string> Search(Folder input, string searchString)
{
var paths = new List<string>();
var currentPath = input.root;
foreach (var child in input.children)
{
if (child.root == searchString)
{
var fullPath = Path.Combine(currentPath, child.root);
paths.Add(fullPath);
}
var childPaths = Search(child, searchString);
foreach (var path in childPaths)
{
var fullPath = Path.Combine(currentPath, path);
paths.Add(fullPath);
}            
}
return paths;
}

在提供的示例上运行此操作会产生收益:

foldersub-folder2sub-folder3

最新更新