In this blog, we will learn how to Iterate backward through a List in C# using below easy methods,
- Using
List<T>.Reverse()
method andforeach
loop - Using
for
loop
Using List<T>.Reverse()
method and foreach
loop
In this example, we are using foreach
loop and List<T>.Reverse()
method to iterate backward in a list in C#. List<T>.Reverse()
method is used to reverse the order of the given element and foreach
loop is used to iterate the element and display it using Console.WriteLine()
as shown below,
using System;
using System.Collections.Generic;
namespace ReverseOrder
{
class Program
{
static void Main()
{
List<int> numbers = new List<int>() { 1, 2, 3, 4, 5, 6, 7 };
// Reverse the order of the elements
foreach (int i in numbers.Reverse())
{
// Display the element
Console.WriteLine(i);
}
Console.ReadKey();
}
}
}
Output:
7
6
5
4
3
2
1
Using for
loop
Using for
loop is a very simple method to iterate backward through a list in C#. We just start from the last index to the first index and display the each element using Console.WriteLine().
using System;
using System.Collections.Generic;
namespace ReverseOrder
{
class Program
{
static void Main()
{
List<int> numbers = new List<int>() { 1, 2, 3, 4, 5, 6, 7 };
// Reverse the order of the elements using for loop
for (var i = numbers.Count - 1; i >= 0; i--)
{
// Display the element
Console.WriteLine(numbers[i]);
}
Console.ReadKey();
}
}
}
Output:
7
6
5
4
3
2
1
Comments (0)