#600 – Reversing the Elements in an Array

You can use the static Array.Reverse method to reverse the order of elements in an array.  This modifies the contents of the array that you pass to Array.Reverse.

            int[] someNumbers = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
            DumpArrayContents(someNumbers);

            // Reverse the elements using Array.Reverse
            Array.Reverse(someNumbers);
            DumpArrayContents(someNumbers);

Note that this Reverse method is different from the IEnumerable<int>.Reverse method, which does not modify the contents of the array, but just returns a reversed sequence.

// IEnumerable<int>.Reverse
int[] moreNumbers = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
IEnumerable<int> reversedNums = moreNumbers.Reverse();
DumpArrayContents(moreNumbers);
DumpArrayContents(reversedNums);

Advertisement

#564 – Use the Reverse Method to Iterate Backwards through a Collection

You can use the Enumerable<TSource>.Reverse method on any enumerable object, to iterate backwards through its collection.

Because arrays and collections implement the IEnumerable interface, you can use a foreach statement to enumerate through their elements in a forward-only fashion.

            int[] nums = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

            foreach (int i in nums)
                Console.WriteLine(i);

The default enumerator implemented in types like System.Array and List<T>, however, only allows you to iterate forwards through a collection.  If you instead want to iterate backwards through an array or collection, you can use the Reverse method mentioned above. This method is part of System.Linq and is an extension method that works on any IEnumerable<T> type.

            int[] nums = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

            foreach (int j in nums.Reverse())
                Console.WriteLine(j);

            List<Dog> myDogs = new List<Dog>();
            myDogs.Add(new Dog("Jack", 17));
            myDogs.Add(new Dog("Kirby", 15));
            myDogs.Add(new Dog("Ruby", 1));

            foreach (Dog d in myDogs.Reverse<Dog>())
                Console.WriteLine(d.Name);

#392 – Reversing a String Using the Reverse Method

Starting with .NET 3.5, you can use a number of extension methods that are part of the System.Linq namespace to act upon any type that implements IEnumerable<T>.  This includes the string type in C# (System.String), which implements IEnumerable<char>.

One of the most useful extension methods that comes with Linq is the Reverse method (Enumerable.Reverse<TSource>).  Because this is an extension method, you can use it on an instance of a string as if it were an instance method.

            string funnyMan = "Roscoe Arbuckle";

            string backwardsGuy = new string(funnyMan.Reverse().ToArray());

Because Reverse returns an object of type ReverseIterator<char>, we need to convert it back to an array and then use the array to instantiate a new string.