9.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.
Solution
Use two loops; one to iterate over rows, the other to iterate over columns:
public static void Reverse2DimArray(int[,] theArray) { for (int rowIndex = 0; rowIndex <= (theArray.GetUpperBound(0)); rowIndex++) { for (int colIndex = 0; colIndex <= (theArray.GetUpperBound(1) / 2); colIndex++) { int 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
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); } }
This method displays the following:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 3 ← Note that each row of 3 elements are reversed 2 1 6 ← This is the start of the next row 5 4 9 8 7 12 11 10 15 14 13
The Reverse2DimArray
method uses the same logic
presented in the previous recipe to reverse the array; however, a
nested for
loop is used instead of a single
for
loop. The outer for
loop iterates over each ...
Get C# Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.