Sabari M Sabari M
Updated date Feb 14, 2023
This blog explains how to Iterate backward through a List in C# and helps the people who learn C#

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

Sabari M
Sabari M
Software Professional, India

IT professional with 15+ years of experience in Microsoft Technologies with a strong base in Microsoft .NET (C#.Net, ASP.Net MVC, ASP.NET WEB API, Webservices,...Read More

https://www.techieclues.com/profile/alagu-mano-sabari-m

Comments (0)

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