Sponsored by Gluten Free Waffles and Sliced Bananas

Monday, March 18, 2013

Simple Reverse Iterations in C#

11:05 AM Posted by Tyson Nero No comments
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--)  
 {  
   Console.WriteLine(names[i]);  
 }  

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

 foreach (var name in names.Reverse())  
 {  
   Console.WriteLine(name);  
 }  

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

0 comments:

Post a Comment