
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
286
|
Chapter 5: Collections
5.3 Reversing a Two-Dimensional Array
Problem
You need to reverse each row in a two-dimensional array. The Array.Reverse method
does not support this operation.
Solution
Use the following Reverse2DimArray<T> method:
public static void Reverse2DimArray<T>(T[,] theArray)
{
for (int rowIndex = 0; rowIndex <= (theArray.GetUpperBound(0)); rowIndex++)
{
for (int colIndex = 0;
colIndex <= (theArray.GetUpperBound(1) / 2);
colIndex++)
{
T tempHolder = theArray[rowIndex, colIndex];
theArray[rowIndex, colIndex] =
theArray[rowIndex, theArray.GetUpperBound(1) - colIndex];
theArray[rowIndex, theArray.GetUpperBound(1) - colIndex] = tempHolder;
}
}
}
Discussion
The following TestReverse2DimArray method shows how the Reverse2DimArray<T>
method is used:
public static void TestReverse2DimArray( )
{
int[,] someArray =
new int[5,3] {{1,2,3},{4,5,6},{7,8,9},{10,11,12},{13,14,15}};
// Display the original array.
foreach (int i in someArray)
{
Console.WriteLine(i);
}
Console.WriteLine( );
Reverse2DimArray(someArray);
// Display the reversed array.
foreach (int i in someArray)
{
Console.WriteLine(i);
}
}