EN
C# / .NET - reverse List
0
points
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.