Using c#, how to iterate through an multidimensional array of unknown dimensions?
For example consider setting each element of the array to a specified value, all entries of the array needs to be iterated. The method should handle all the following cases and fill all entries with the value 4, regardless of the dimension of the array passed.
ClearArray(new int[3], 4);
ClearArray(new int[3,3], 4);
ClearArray(new int[3, 3, 3, 3], 4);
The methods signature obviously looks something like
static void ClearArray(Array a, int val) { ... }
I know how to iterate through one dimension:
for (int i=0; i<a.GetLength(dimension); i++)
{
...
}
Note: This question is not about 2D arrays, 3D arrays, nor 4D arrays. It should handle whatever dimension the Rank
property on the Array
object says.
Use Lexicographical order:
Index is sequence of "digits". On each iteration last "digit" incremented while it in bounds, then next "digit" incremented, etc
Func<Array, int[]> firstIndex =
array => Enumerable.Range(0, array.Rank)
.Select(_i => array.GetLowerBound(_i))
.ToArray();
Func<Array, int[], int[]> nextIndex = (array, index) =>
{
for (int i = index.Length-1; i >= 0; --i)
{
index[i]++;
if (index[i] <= array.GetUpperBound(i))
return index;
index[i] = array.GetLowerBound(i);
}
return null;
};
for (var index = firstIndex(array); index != null; index = nextIndex(array, index))
{
var v = array.GetValue(index);
...
array.SetValue(newValue, index);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With