即使在“.ToList()”调用之后,递归中的yield返回也不返回值

时间:2016-05-29 19:34:43

标签: c# recursion permutation yield

当我调用生成排列时,第二个GeneratePermutations(list, startCount, permutationCount)会产生6次返回(yield return permutationList;)。但由于某些原因,即使我在结果上调用result,第一个GetPermutations中的.ToList()也不包含任何内容。

这有什么要做的递归吗?

Test.cs

IEnumerable<int[]> actual = _sut.GetPermutations(3).ToList();

Perm.cs

public class Perm
{
    public IEnumerable<int[]> GetPermutations(int permutationCount)
    {
        int[] permutationList = Enumerable.Range(1, permutationCount).ToArray();
        IEnumerable<int[]> result = GeneratePermutations(permutationList, 0, permutationCount - 1).ToList();

        // Doesn't contain any value!
        return result;
    }

    // http://stackoverflow.com/a/756083/4035
    private IEnumerable<int[]> GeneratePermutations(int[] permutationList, int startCount, int permutationCount)
    {
        if (startCount == permutationCount)
        {
            // Does return 6 times here.
            yield return permutationList;
        }
        else
        {
            for (int i = startCount; i <= permutationCount; i++)
            {
                Swap(ref permutationList, startCount, i);
                GeneratePermutations(permutationList, startCount + 1, permutationCount).ToList();
                Swap(ref permutationList, startCount, i);
            }

        }
    }

    // http://stackoverflow.com/a/2094316/4035
    public static void Swap(ref int[] list, int index1, int index2)
    {
        int tmp = list[index1];
        list[index1] = list[index2];
        list[index2] = tmp;
    }
}

1 个答案:

答案 0 :(得分:3)

您的问题是,您永远不会返回递归调用的结果,并且您始终使用相同的数组。这对您的代码来说是最快的解决方案(不是最好的,但我确定你会从这里弄清楚):

IEnumerable<int[]> perms = GeneratePermutations(
    new List<int>(permutationList).ToArray(), 
    startCount + 1, permutationCount);

foreach(int[] perm in perms)
    yield return perm;

btw:你可以让整个班级成为静态和通用的

Proof on dotNetFiddle