#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);

Advertisement

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: