#564 – Use the Reverse Method to Iterate Backwards through a Collection
April 18, 2012 Leave a comment
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);