如何爆发递归调用
本文关键字:递归 调用 爆发 何爆发 | 更新日期: 2023-09-27 18:16:10
如何分解递归:
callGetDirectory("D:'Engine'", "102")
期望输出:D:'Engine'Type'Tone_Id_102
谢谢你。
private static string GetDirectory(string folderPath, string number)
{
foreach (string directory in Directory.GetDirectories(folderPath))
{
if (directory.Contains(number))
{
return directory;
}
GetDirectory(directory, number);
}
return null;
}
这样做不是更容易更好吗
return Directory.EnumerateDirectories(
folderPath,
"*",
SearchOption.AllDirectories)
.FirstOrDefault(s => s.Contains(number))
或者像@TimSchmelter建议的,
return Directory.EnumerateDirectories(
folderPath,
string.Format("*{0}*", number),
SearchOption.AllDirectories)
.FirstOrDefault()
应该这样做:
private static string GetDirectory(string folderPath, string number)
{
foreach (string directory in Directory.GetDirectories(folderPath))
{
if (directory.Contains(number))
return directory;
var innerDir = GetDirectory(directory, number);
if (innerDir != null)
return innerDir;
}
return null;
}
做同样的事情,我认为它更可读:
Directory.GetDirectories(folderPath, "*.*", SearchOption.AllDirectories)
.FirstOrDefault(x => x.Contains(number));
我认为你只需要一个return
:
return GetDirectory(directory, number);
这将遍历foreach
中的一个条目,所以这样更好:
private static string GetDirectory(string folderPath, string number)
{
foreach (string directory in Directory.GetDirectories(folderPath))
{
if (directory.Contains(number))
{
return directory;
}
string result = GetDirectory(directory, number);
if (!string.IsNullOrEmpty(result))
{
return result;
}
}
return null;
}