Languages
[Edit]
EN

C# / .NET - reverse List

0 points
Created by:
Elleanor-Williamson
380

In this article, we would like to show you how to reverse List in C#.

Quick solution:

List<int> myList = new List<int> { 1, 2, 3 };

myList.Reverse();

or:

List<int> myList = new List<int> { 1, 2, 3 };

for (int i = 0; i < myList.Count / 2; i++)
{
    int tmp = myList[i];
    myList[i] = myList[myList.Count - i - 1];
    myList[myList.Count - i - 1] = tmp;
}

 

Practical example

In this example, we use Reverse() method to reverse List.

using System;
using System.Collections.Generic;

public class Program
{
    public static void Main()
    {
        List<int> myList = new List<int> { 1, 2, 3 };

        // reverse List
        myList.Reverse();

        // display result
        foreach (int item in myList)
            Console.WriteLine(item);
    }
}

Output:

3
2
1

2. Without Reverse() method

In this example, we use simple for loop to reverse List.

using System;
using System.Collections.Generic;

public class Program
{
    public static void Main()
    {
        List<int> myList = new List<int> { 1, 2, 3 };

        // reverse myList
        for (int i = 0; i < myList.Count / 2; i++)
        {
            int tmp = myList[i];
            myList[i] = myList[myList.Count - i - 1];
            myList[myList.Count - i - 1] = tmp;
        }

        // display result
        foreach (int item in myList)
            Console.WriteLine(item);
    }
}

Output:

3
2
1

Note:

We only iterate through half the length of the List, otherwise it will be reversed twice.

References

  1. 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