Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reversing order of elements in multidimensional array

Tags:

arrays

c#

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;
like image 687
Thomas Avatar asked Dec 08 '25 06:12

Thomas


2 Answers

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();
like image 89
Adam Rackis Avatar answered Dec 09 '25 19:12

Adam Rackis


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

like image 33
Waqas Raja Avatar answered Dec 09 '25 20:12

Waqas Raja