Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Reverse the order of the elements in the entire List or in the specified range in C#
The List<T>.Reverse() method in C# allows you to reverse the order of elements in a List. You can reverse the entire list or reverse a specific range of elements within the list.
Syntax
Following is the syntax for reversing the entire list −
list.Reverse();
Following is the syntax for reversing a specified range of elements −
list.Reverse(int index, int count);
Parameters
index − The zero-based starting index of the range to reverse.
count − The number of elements in the range to reverse.
Using Reverse() for Entire List
Example
using System;
using System.Collections.Generic;
public class Demo {
public static void Main(String[] args) {
List<int> list = new List<int>();
list.Add(5);
list.Add(10);
list.Add(20);
list.Add(50);
list.Add(100);
Console.WriteLine("Original List:");
foreach (int i in list) {
Console.WriteLine(i);
}
list.Reverse();
Console.WriteLine("\nReversed List:");
foreach (int i in list) {
Console.WriteLine(i);
}
}
}
The output of the above code is −
Original List: 5 10 20 50 100 Reversed List: 100 50 20 10 5
Using Reverse() for Specified Range
Example
using System;
using System.Collections.Generic;
public class Demo {
public static void Main(String[] args) {
List<String> list = new List<String>();
list.Add("One");
list.Add("Two");
list.Add("Three");
list.Add("Four");
list.Add("Five");
list.Add("Six");
list.Add("Seven");
list.Add("Eight");
Console.WriteLine("Original List:");
foreach (string res in list) {
Console.WriteLine(res);
}
list.Reverse(2, 4);
Console.WriteLine("\nReversed 4 elements starting from index 2:");
foreach (string res in list) {
Console.WriteLine(res);
}
}
}
The output of the above code is −
Original List: One Two Three Four Five Six Seven Eight Reversed 4 elements starting from index 2: One Two Six Five Four Three Seven Eight
Common Use Cases
Sorting in descending order − First sort the list, then reverse it.
Undo operations − Reverse a portion of the list to restore previous state.
Algorithm implementations − Many algorithms require reversing portions of arrays or lists.
Data display − Show most recent items first by reversing chronologically ordered data.
Conclusion
The List<T>.Reverse() method provides an efficient way to reverse elements in a List. Use Reverse() to reverse the entire list or Reverse(index, count) to reverse only a specific range of elements, making it useful for various data manipulation scenarios.
