Thomas
Thomas

Reputation: 2615

Reversing order of elements in multidimensional array

I have an array with elemnents in order 1,2,3,4,5 and I would need to reverse it so it will be 5,4,3,2,1. What about the following pseudo code? Is here not an easier way
EDIT: I Am sorry I thought multidimensional array

    someclass [,] temporaryArray=new someclass [ArrayLenght,ArrayLenght];


   //for each dimension then
    for(int I=0;I<ArrayLenghtOfDimension;I++)
    {
      temporaryArray[ArrayLenghtOfDimension-I]=Array[I];

    }

    Array=temporaryArray;

Upvotes: 2

Views: 4993

Answers (5)

Adam Rackis
Adam Rackis

Reputation: 83358

For a multi-dimensional array it's the same idea

int[][] multiDimArray = new int[][] { new int[] { 1, 2, 3 }, new int[] { 4, 5, 6 } };
int[][] reversedMultiArray = multiDimArray.Reverse().ToArray();

produces an array of two arrays that is: {4, 5, 6}, {1, 2, 3}

Upvotes: 0

Oded
Oded

Reputation: 498972

Event though the Array class has Reverse methods defined:

Array.Reverse(originalArray); // original array is now reversed

If all you need to do is iterate backwards over it do the following:

for(int I= ArrayLength - 1; I >= 0; I--)
{

}

This avoid re-allocating memory for the reversed array.

Upvotes: 2

Abhijeet Patel
Abhijeet Patel

Reputation: 6868

Array.Reverse is the best way to do this. Do you care about order of the elements at all? If so,then you can do the following.

 int[] originalArray = new int[] { 10, 2, 13, 4, 5 };
 int[] descOrderedArray = originalArray.OrderByDescending(i => i).ToArray();
 int[] ascOrderedArray =   originalArray.OrderBy(i => i).ToArray();

Upvotes: 1

Adam Rackis
Adam Rackis

Reputation: 83358

The array base class has a Reverse() extension method built in

int[] originalArray = new int[] { 1, 2, 3, 4, 5 };
int[] reversedArray = originalArray.Reverse().ToArray();

Note that the Reverse method returns IEnumerable, so you need to call ToArray() on the result.

And if you need to just iterate over the elements in the array, then all you need is

foreach (int element in originalArray.Reverse())
                Console.WriteLine(element);

Oops - Reverse is on IEnumerable, not Array, so you can use that with any collection.

IEnumerable<int> IEnumerableInt = new List<int>() { 1, 2, 3 };
int[] reversedArray2 = IEnumerableInt.Reverse().ToArray();

Upvotes: 4

Waqas Raja
Waqas Raja

Reputation: 10872

Yes there is fast solution exists in .net

int[] values = new int[] { 1, 2, 3, 4, 5 };

Array.Reverse(values);

Your array is reversed. so you can iterate through it

foreach (int i in values)
{
    Response.Write(i.ToString());
}

the above code will display 54321

It will also work for string[], char[] or other type of arrays

Upvotes: 2

Related Questions