It sounds like what you want is to end up with is arrays containing the second elements of the 2D arrays, grouped by the first element. So given your example, you want results like this:
Iteration 1a: {"1", "b", "b", "b"}
Iteration 1b: {"b", "c", "c", "c"}
Iteration 2a: {"2", "b", "b", "e"}
Iteration 2b: {"b", "c", "c", "d"}
Understand that this cannot be achieved efficiently, because a 2D array is not stored as multiple arrays, but instead as a singular block of memory. In memory, your array will look this this:
"1", "b", "b", "b", "b", "c", "c", "c", "2", "b", "b", "e", "b", "c", "c", "d"
And when you access it with a[y, x]
, the correct element is chosen by y * a.GetLength(0) + x
.
If you really want an array of arrays, then you should use [][]
instead of [,]
, which is what others have suggested. If, on the other hand, you're stuck with the multidimensional array for other reasons, then you'll have to build or fake the inner arrays.
To build the inner arrays:
foreach(string[,] square in cross)
for(int y = 0; y < square.GetUpperBound(0); y++){
string[] inner = new string[square.GetLength(1)];
for(int x = 0; x < inner.Length; x++)
inner[x] = square[y, x];
// now do something with inner
}
That's pretty inefficient, though, so you're better off faking it. If you only need to iterate through it later, then you can create an enumerable:
foreach(string[,] square in cross)
for(int y = 0; y < square.GetUpperBound(0); y++){
var inner = GetEnumeratedInner(square, y);
// now do something with inner
}
...
static IEnumerable<string> GetEnumeratedInner(string[,] square, int y){
for(int x = 0; x < square.GetUpperBound(1); x++)
yield return square[y, x];
}
If you really need to access it by index, as you could with an array, then an indexed class will do the trick:
foreach(string[,] square in cross)
for(int y = 0; y < square.GetUpperBound(0); y++){
var inner = new IndexedInner(square, y);
// now do something with inner
}
...
// this class should really implement ICollection<T> and System.Collections.IList,
// but that would be too much unimportant code to put here
class IndexedInner<T> : IEnumerable<T>{
T[,] square;
int y;
public IndexedInner(T[,] square, int y){
this.square = square;
this.y = y;
}
public int Length{get{return square.GetLength(1);}}
public T this[int x]{
get{return square[y, x];}
set{square[y, x] = value;}
}
public IEnumerator<T> GetEnumerator(){
for(int x = 0; x < square.GetUpperBound(1); x++)
yield return square[y, x];
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator(){
return GetEnumerator();
}
}