Although this problem seems simple on the surface, it is actually more complex than it looks. However, recognizing that visiting each position in a multidimensional (or even cogged) array is a Cartesian operation of the product on a set of array indices, we can simplify the solution ... and ultimately write a more elegant solution.
We are going to use Eric Lippert LINQ Cartesian Product to make a heavy lift. You can read more about how this works on your blog if you want.
While this implementation is specific to visiting the cells of a multidimensional array, it should be relatively easy to see how to expand it to visit the notched array.
public static class EnumerableExt
{
public static IEnumerable<IEnumerable<T>> CartesianProduct<T>(
this IEnumerable<IEnumerable<T>> sequences)
{
IEnumerable<IEnumerable<T>> emptyProduct =
new[] { Enumerable.Empty<T>() };
return sequences.Aggregate(
emptyProduct,
(accumulator, sequence) =>
from accseq in accumulator
from item in sequence
select accseq.Concat(new[] { item }));
}
}
class MDFill
{
public static void Main()
{
Array mdArray = new int[2,3,4,5];
var dimensionBounds =
Enumerable.Range(0, mdArray.Rank)
.Select(x => Enumerable.Range(mdArray.GetLowerBound(x),
mdArray.GetUpperBound(x) - mdArray.GetLowerBound(x)+1));
int someValue = 100;
foreach( var indexSet in dimensionBounds.CartesianProduct() )
{
mdArray.SetValue( someValue, indexSet.ToArray() );
}
}
}
, , ... , .