In this tutorial, we will learn about sorting operator - Reverse in LINQ
In LINQ, the Reverse operator is used to reverse the order of the items in the sequence or collection. This operator simply inverted the sequence of items without requiring loops or additional logic. This operator does not modify the existing collection instead of this, it returns the new collection.
For instance, you have an integer array in ascending order, by using the Reverse() method, it simply reverses the order of the array in descending order.
The Reverse()
method exists in two different namespaces:
System.Linq
Namespace:IEnumerable<TSource>
interface.IEnumerable<TSource>
type.System.Collections.Generic
Namespace:Here is an example of reversing an array which contains the following elements: 60, 80, 50, 90, 10, 30, 70, 40, 20, 100, 110 and 120. We’ll apply the Reverse()
method to this array and observe the results:
using System;
using System.Linq;
namespace LINQDemo
{
public class LinqPrograms
{
public static void Main(string[] args)
{
int[] intNumbers = new int[] { 60, 80, 50, 90, 10, 30, 70, 40, 20, 100, 110, 120 };
//Original Array
Console.WriteLine("Original Array:");
foreach(int item in intNumbers){
Console.Write(item + " ");
}
//Reverse Using Method Syntax
var MSTotalCount = intNumbers.Reverse();
Console.WriteLine("\n\nReverse using Method Syntax:");
foreach(int item in MSTotalCount){
Console.Write(item + " ");
}
//Reverse Using Mixed Syntax
var QSTotalCount = (from num in intNumbers
select num).Reverse();
Console.WriteLine("\n\nReverse using using Mixed Syntax: ");
foreach(int item in QSTotalCount){
Console.Write(item + " ");
}
}
}
}
Original Array:
60 80 50 90 10 30 70 40 20 100 110 120
Reverse using Method Syntax:
120 110 100 20 40 70 30 10 90 50 80 60
Reverse using using Mixed Syntax:
120 110 100 20 40 70 30 10 90 50 80 60
The System.Collections.Generic
namespace provides an in-place reversal method. Although it doesn’t return a new collection, it modifies the existing collection. Here’s is an example of Reverse()
method of System.Collections.Generic
namespace:
using System;
using System.Collections.Generic;
namespace LINQDemo
{
public class LinqPrograms
{
public static void Main(string[] args)
{
List<int> intNumbers = new List<int> { 60, 80, 50, 90, 10, 30, 70, 40, 20, 100, 110, 120 };
//Original Array
Console.WriteLine("Original Array:");
foreach(int item in intNumbers){
Console.Write(item + " ");
}
//Reverse using Reverse Method of System.Collections.Generic
intNumbers.Reverse();
Console.WriteLine("\n\nAfter Reverse (In-Place):");
foreach (var item in intNumbers)
{
Console.Write(item + " ");
}
}
}
}
Original Array:
60 80 50 90 10 30 70 40 20 100 110 120
After Reverse (In-Place):
120 110 100 20 40 70 30 10 90 50 80 60
Learn Grouping Operators - GroupBy & ToLookup in the next tutorial.