TechieClues TechieClues
Updated date Feb 14, 2023
This blog explains how to Iterate backward through a List in C# and helps the people who learn C#
  • 3.5k
  • 0
  • 0

In this blog, we will learn how to Iterate backward through a List in C# using below easy methods,

  • Using List<T>.Reverse() method and foreach 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

ABOUT THE AUTHOR

TechieClues
TechieClues

I specialize in creating and sharing insightful content encompassing various programming languages and technologies. My expertise extends to Python, PHP, Java, ... For more detailed information, please check out the user profile

https://www.techieclues.com/profile/techieclues

Comments (0)

There are no comments. Be the first to comment!!!