I’m looking for a way to set every value in a multidimensional array to a single value. The problem is that the number of dimensions is unknown at compile-time – it could be one-dimensional, it could be 4-dimensional. Since foreach doesn’t let you set values, what is one way that I could achieve this goal? Thanks much.
I’m looking for a way to set every value in a multidimensional array to
Share
While this problem appears simple on the surface, it’s actually more complicated than it looks. However, by recognizing that visiting every position in a multidimensional (or even jagged) array is a Cartesian product operation on the set of indexes of the array – we can simplify the solution … and ultimately write a more elegant solution.
We’re going to leverage Eric Lippert’s LINQ Cartesian Product implementation to do the heavy lifting. You can read more about how that works on his blog if you like.
While this implementation is specific to visiting the cells of a multidimensional array – it should be relatively easy to see how to extend it to visit a jagged array as well.
It’s now trivial to factor this code out into a reusable method that can be used for either jagged or multidimensional arrays … or any data structure that can be viewed as a rectangular array.