Iterate backwards in a List in C#
This post will discuss how to iterate backwards in a List in C#.
1. Using for loop
A simple solution to iterate backwards in a list in C# is using a regular for-loop. The idea is to start from the last index to the first index and process each item. This would translate to the following code:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
using System; using System.Collections.Generic; public class Example { public static void Main() { List<int> nums = new List<int>() { 1, 2, 3, 4, 5 }; for (var i = nums.Count - 1; i >= 0; i--) { Console.WriteLine(nums[i]); } } } |
Output:
5
4
3
2
1
Alternatively, you can create an extension method for getting a sequence of elements in the list in reverse order. Here’s what the code would look like:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
using System; using System.Collections.Generic; static class Extensions { public static IEnumerable<T> ReverseList<T>(this List<T> items) { for (int i = items.Count-1; i >= 0; i--) { yield return items[i]; } } } public class Example { public static void Main() { List<int> nums = new List<int>() { 1, 2, 3, 4, 5 }; var reverse = nums.ReverseList(); foreach (var i in reverse) { Console.WriteLine(i); } } } |
Output:
5
4
3
2
1
2. Using foreach loop
An alternative way to iterate backwards in a list is to reverse the list with the List.Reverse() method and iterate over the reversed list using the foreach statement. Note that this approach is not recommended as it changes the original order of the list.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
using System; using System.Collections.Generic; public class Example { public static void Main() { List<int> nums = new List<int>() { 1, 2, 3, 4, 5 }; nums.Reverse(); foreach (var i in nums) { Console.WriteLine(i); } } } |
Output:
5
4
3
2
1
That’s all about iterating backwards in a List in C#.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)