Summary: in this tutorial, you will learn how to reverse a sequence using the LINQ Reverse()
method.
Introduction to the LINQ Reverse() method
The Reverse()
method allows you to inver the order of elements in a sequence. Here’s the syntax of the Reverse()
method:
IEnumerable<TSource> Reverse<TSource> (
this IEnumerable<TSource> source
);
Code language: C# (cs)
In this syntax:
TSource
is the type of element of thesource
sequence.source
is anIEnumerable<TSource>
that represents the input sequence.
The Reverse()
method returns a new sequence that mirrors the source
sequence by arranging its elements in reverse order.
The Reverse()
method throws an ArgumentNullException
if the source
sequence is null.
LINQ Reverse() method example
Let’s take some examples of using the Reverse()
method
1) Using LINQ Reverse() method to reverse a list of integers
The following example shows how to use the Reverse()
method to reverse a list of integers:
using static System.Console;
var numbers = new List<int>() { 1, 2, 3 };
var reversedNums = Enumerable.Reverse(numbers);
foreach (var number in reversedNums)
{
WriteLine(number);
}
Code language: C# (cs)
Output:
3
2
1
Code language: plaintext (plaintext)
2) Using LINQ Reverse() method to reverse a list of strings
The following example illustrates how to use the Reverse()
method to reverse a list of strings:
using static System.Console;
var words = new List<string>() { "Hello","World" };
var reversedWords = Enumerable.Reverse(words);
foreach (var word in reversedWords)
{
WriteLine(word);
}
Code language: C# (cs)
Output:
World
Hello
Code language: plaintext (plaintext)
Summary
- Use LINQ
Reverse()
method to return a new sequence that contains elements of an input sequence but in a reversed order.
Was this tutorial helpful ?