I have a two-dimensional object[,] array which contains a matrix of rows and columns (object[nRows, nColumns]).
I would like to chunk this into a batch of rows - e.g. batches of 1,000 rows each which I can enumerate over.
In summary, I am looking for C# code that does the following but for two dimensional arrays (source):
private IEnumerable<T[]> SplitArray<T>(T[] sourceArray, int rangeLength)
{
int startIndex = 0;
do
{
T[] range = new T[Math.Min(rangeLength, sourceArray.Length - startIndex)];
Array.Copy(sourceArray, startIndex, range, 0, range.Length);
startIndex += rangeLength;
yield return range;
}
while (startIndex < sourceArray.Length);
}
This attempt at adapting the code for [,] arrays fails - rows/columns begin to get jumbled-up after the first iteration:
private IEnumerable<T[,]> SplitArray<T>(T[,] sourceArray, int rangeLength)
{
int startIndex = 0;
do
{
T[,] range = new T[Math.Min(rangeLength, sourceArray.GetLength(0) - startIndex), sourceArray.GetLength(1)];
Array.Copy(sourceArray, startIndex, range, 0, range.Length);
startIndex += rangeLength;
yield return range;
}
while (startIndex < sourceArray.GetLength(0));
}
[,]arrays?)sourceArray.GetLength(0) - startIndexas you did there. Also,startIndex += rangeLengthdoesn't make much sense, either, because you just copied range.Length elements, not rangeLength elements (as you seem to use rangeLength only as a range for one dimension in your 2D array)