EN
C# / .NET - iterate through a List in reverse order
0
points
In this article, we would like to show you how to iterate through a List in reverse order in C#.
Quick solution:
List<string> myList = new List<string> { "A", "B", "C" };
for (int i = myList.Count - 1; i >= 0; i--)
Console.WriteLine(myList[i]);
or:
List<string> myList = new List<string> { "A", "B", "C" };
myList.Reverse();
foreach (string item in myList)
Console.WriteLine(item);
1. Practical example using for
loop
In this example, we use reversed for loop to iterate through myList
in reverse order.
using System;
using System.Collections.Generic;
public class Program
{
public static void Main()
{
List<string> myList = new List<string> { "A", "B", "C" };
for (int i = myList.Count - 1; i >= 0; i--)
Console.WriteLine(myList[i]);
}
}
Output:
C
B
A
2. Using foreach
with reversed List
In this example, we use Reverse()
method to reverse myList
, then we iterate through its items using foreach
.
using System;
using System.Collections.Generic;
public class Program
{
public static void Main()
{
List<string> myList = new List<string> { "A", "B", "C" };
myList.Reverse();
foreach (string item in myList)
{
Console.WriteLine(item);
}
}
}
Output:
C
B
A