Looping over jagged arrays in c# --- using foreach instead of for?
arrays, c#, for-loop, foreach, loops
Solution
The following code is "neater":
OutputArray = InputArray.Select(x => x.Select(y => someFunction(y)).ToArray())
.ToArray();
But I would just go with the loops, because this LINQ version has a significant disadvantage: It creates new arrays instead of using the existing ones in `OutputArray`. This argument is moot if you create `OutputArray` right before the loop you showed us. Furthermore, it is quite a lot harder to read.
Problem
I'm working on a project, and I find myself repeatedly looping over a jagged array using nested `for` loops. I'm wondering if there might be a neater way of doing it using `foreach`? Here's what I mean: ``` for (int ii = 0; ii < xDimension; ii++) { for (int jj = 0; jj < yDimension; jj++) { OutputArray[ii][jj] = someFunction(InputArray[ii][jj]); } } ``` Note that I'm using Jagged arrays even though my data is of fixed size because jagged arrays are faster than multidimensional arrays. Unfortunately speed is an issue with this project so unfortunately performance will outweigh my own OCD coding desires. Is there a way to do this with `foreach` that avoids the nested `for` loops but puts the output data in the correct place in the `OutputArray`? Wwould there be any benefit/loss from doing so (if it is possible) other than having slightly neater code?