如何打破递归调用

时间:2014-08-04 08:58:23

标签: c# recursion

如何突破递归,如下所示:

致电GetDirectory("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;
}

4 个答案:

答案 0 :(得分:2)

这样做不会更容易也更好吗

return Directory.EnumerateDirectories(
        folderPath,
        "*",
        SearchOption.AllDirectories)
    .FirstOrDefault(s => s.Contains(number))

或@TimSchmelter建议,

return Directory.EnumerateDirectories(
        folderPath,
        string.Format("*{0}*", number),
        SearchOption.AllDirectories)
    .FirstOrDefault()

答案 1 :(得分:1)

我认为你只需要一个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;
}

答案 2 :(得分:1)

这应该这样做:

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;
}

答案 3 :(得分:1)

这也是一样的,我认为它更具可读性:

Directory.GetDirectories(folderPath, "*.*", SearchOption.AllDirectories)
         .FirstOrDefault(x => x.Contains(number));