Sponsored by Gluten Free Waffles and Sliced Bananas

Monday, March 18, 2013

Simple Reverse Iterations in C#

11:05 AM Posted by Tyson Nero 1 comment
There are some situations that require the use of iterating in reverse. It's not such a hard concept to iterate backwards, however, there are cases where using the syntax of a for loop isn't the most satisfactory method. Thankfully, in .NET 3.5 the Reverse() extension method was added, which allows you to simply use a for each in cases where you want minimal code pollution such as an ASP.NET MVC view.

Let's say you have this simple array:

 string[] names = { "Barry", "Bob", "Bill" };  

Here is an example of using a for loop to do a traditional reverse iteration:

 for (int i = names.Length - 1; i >= 0; i--)  

Now, here's an example of using the .NET 3.5 Linq extension:

 foreach (var name in names.Reverse())  

Note: Using the Reverse() method is actually slower. So, use with caution when speed at the lowest level is not a factor.

1 comment:

  1. Hi, Great.. Tutorial is just awesome..It is really helpful for a newbie like me.. I am a regular follower of your blog. Really very informative post you shared here. Kindly keep blogging. If anyone wants to become a .Net developer learn from Dot Net Training in Chennai. or learn thru Dot Net Training in Chennai. Nowadays Dot Net has tons of job opportunities on various vertical industry.
    or Javascript Training in Chennai. Nowadays JavaScript has tons of job opportunities on various vertical industry.