I'm trying to write a method that enumerates all sequences that can be used in a for loop.
Assume IEnumerable<int>[] intValues
is the original collection if integers and let's say it is:
intValues[0] = int[] {1, 2, 3}
intValues[1] = int[] {4, 5}
I need to write EnumerateSequences(...)
such that:
foreach (int[] seq in EnumerateSequences(...))
{
// 1st iteration: seq = [1, 4]
// 2nd iteration: seq = [1, 5]
// 3rd iteration: seq = [2, 4]
// 4th iteration: seq = [2, 5]
// 5th iteration: seq = [3, 4]
// 6th iteration: seq = [3, 5]
}
I came up with this method, however, EnumerateSequences(intValues, 0, null)
won't recurse inside so it always returns null
:
private static IEnumerable<int[]> EnumerateSequences(IEnumerable<int>[] intValues, int pos, int[] seq)
{
if (pos < intValues.Length)
{
foreach (var f in intValues[pos])
{
if (seq == null && pos == 0)
{
seq = new int[intValues.Length];
}
seq[pos] = f;
var _ = EnumerateSequences(intValues, pos + 1, seq);
}
}
else if (pos == intValues.Length || seq == null)
{
yield return seq;
}
}