Languages
[Edit]
EN

C# / .NET - iterate through a List in reverse order

0 points
Created by:
Nabila-Burnett
385

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

References

  1. Iteration statements - C# reference | Microsoft Docs
  2. List<T>.Count Property (System.Collections.Generic) | Microsoft Docs
  3. List<T>.Reverse Method (System.Collections.Generic) | Microsoft Docs
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join