Skip to Content
C# Cookbook
book

C# Cookbook

by Stephen Teilhet, Jay Hilyard
January 2004
Beginner to intermediate
864 pages
22h 18m
English
O'Reilly Media, Inc.
Content preview from C# Cookbook

9.4. Reversing a Jagged Array

Problem

The Array.Reverse method does not provide a way to reverse each subarray in a jagged array. You need this functionality.

Solution

Use the ReverseJaggedArray method:

public static void ReverseJaggedArray(int[][] theArray)
{
    for (int rowIndex = 0; 
      rowIndex <= (theArray.GetUpperBound(0)); rowIndex++)
    {
        for (int colIndex = 0; 
             colIndex <= (theArray[rowIndex].GetUpperBound(0) / 2); 
             colIndex++)
        {
            int tempHolder = theArray[rowIndex][colIndex];                        
            theArray[rowIndex][colIndex] = 
              theArray[rowIndex][theArray[rowIndex].GetUpperBound(0) - 
                      colIndex];   
            theArray[rowIndex][theArray[rowIndex].GetUpperBound(0) - 
                      colIndex] =  tempHolder;      
        }
    }
}

Discussion

The following TestReverseJaggedArray method shows how the ReverseJaggedArray method is used:

public static void TestReverseJaggedArray( )
{
    int[][] someArray = 
      new int[][] {new int[3] {1,2,3}, new int[6]{10,11,12,13,14,15}};

    // Display the original array
    for (int rowIndex = 0; rowIndex < someArray.Length; rowIndex++)
    {
        for (int colIndex = 0; 
          colIndex < someArray[rowIndex].Length; colIndex++)
        {
            Console.WriteLine(someArray[rowIndex][colIndex]);
        }
    }
    Console.WriteLine( );

    ReverseJaggedArray(someArray);

    // Display the reversed array
    for (int rowIndex = 0; rowIndex < someArray.Length; rowIndex++)
    {
        for (int colIndex = 0; 
          colIndex < someArray[rowIndex].Length; colIndex++)
        {
            Console.WriteLine(someArray[rowIndex][colIndex]);
        }
    }
}

This method displays the following:

1
2
3
10
11
12
13
14
15

3     The first reversed subarray
2
1
15   
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

C# Cookbook

C# Cookbook

Joe Mayo
C# Cookbook, 2nd Edition

C# Cookbook, 2nd Edition

Jay Hilyard, Stephen Teilhet
ASP.NET Cookbook

ASP.NET Cookbook

Michael A Kittel, Geoffrey T. LeBlond

Publisher Resources

ISBN: 0596003390Supplemental ContentCatalog PageErrata