我有这段代码搜索给定起始目录的文件夹。找到文件夹后,我需要它的父级名称。下面这段代码可以使用,但它非常难看。我有一个标志,“sessionFound”来帮助打破嵌套的foreach循环。以下作品。我希望我可以对此有所了解,看看我是否可以得到一些关于如何使这个更简洁,更简洁的建议。
感谢。
private void SetProjectFolder(string sessionid)
{
//IoC container gives the root directory to begin search.
string[] supportDirs = Directory.GetDirectories(ApplicationContainer.SupportDirectory);
bool sessionFound = false;
foreach (string directory in supportDirs)
{
if (!sessionFound)
{
foreach (string folder in Directory.GetDirectories(directory))
{
if (!sessionFound)
{
foreach (string productSubFolder in Directory.GetDirectories(folder))
{
if (productSubFolder.Contains(sessionid))
{
_productName = Directory.GetParent(productSubFolder).Parent.Name;
sessionFound = true;
break;
}
}
}
else
{
break;
}
}
}
else
{
break;
}
}
}
答案 0 :(得分:0)
删除sessionFound
后,您最终会得到一个非常清晰明了的代码:
private void SetProjectFolder(string sessionid)
{
//IoC container gives the root directory to begin search.
string[] supportDirs = Directory.GetDirectories(ApplicationContainer.SupportDirectory);
// search for product subfolder
foreach (string directory in supportDirs)
{
foreach (string folder in Directory.GetDirectories(directory))
{
foreach (string productSubFolder in Directory.GetDirectories(folder))
{
if (productSubFolder.Contains(sessionid))
{
// product sub-folder found, set it and exit
_productName = Directory.GetParent(productSubFolder).Parent.Name;
return;
}
}
}
}
// product sub-folder not found
!!! handle error path
}
如果您的目录结构在上述搜索算法意义上是静态的,我认为嵌套的foreach
语句没有问题。也许你可以从中间foreach
开始提取代码到string FindProductSubfolderInFolder(Directory)
之类的单独方法。
答案 1 :(得分:0)
试试这个:
private void SetProjectFolder(string sessionid)
{
//This will simulate the contains statement
string searchPattern = string.Format("*{0}*", sessionid);
string[] supportDirs = Directory.GetDirectories(ApplicationContainer.SupportDirectory, searchPattern);
foreach (string filteredFolder in supportDirs)
{
_productName = Directory.GetParent(filteredFolder).Name;
break;
}
}