System.Linq.Enumerable.Reverse Method

public static IEnumerable<TSource> Reverse<TSource>(this IEnumerable<TSource> source)

Returns a reversed enumerator over the collection.

Parameters

source The sequence to reverse.

Returns

IEnumerable<TSource> An System.Collections.Generic.IEnumerable<TSource> that contains elements in reverse order.

Remarks

If the collection is a List<T>, Array, or ICollection<T>, Reverse is more efficient because it can use the underlying storage to reverse the elements.

If the collection is an IEnumerable<T> that does not implement ICollection<T>, the method iterates through the collection to reverse the elements.

This method defers execution by default. IEnumerable<T> deferred execution.

Exceptions

System.ArgumentNullException source is null.

Examples

Example 1: Reversing a list of integers
This example demonstrates how to reverse a list of integers.
using System; using System.Collections.Generic; using System.Linq; public class Example { public static void Main(string[] args) { List<int> numbers = new List<int> { 1, 2, 3, 4, 5 }; Console.WriteLine("Original list:"); foreach (int number in numbers) { Console.Write(number + " "); } Console.WriteLine(); IEnumerable<int> reversedNumbers = numbers.Reverse(); Console.WriteLine("Reversed list:"); foreach (int number in reversedNumbers) { Console.Write(number + " "); } Console.WriteLine(); } }
// Output: // Original list: // 1 2 3 4 5 // Reversed list: // 5 4 3 2 1
Example 2: Reversing a string
This example shows how to reverse a string by treating it as a sequence of characters.
using System; using System.Collections.Generic; using System.Linq; public class Example { public static void Main(string[] args) { string originalString = "Hello World"; Console.WriteLine("Original string: " + originalString); string reversedString = new string(originalString.Reverse().ToArray()); Console.WriteLine("Reversed string: " + reversedString); } }
// Output: // Original string: Hello World // Reversed string: dlroW olleH