In this tutorial, you will learn:
- What is
Reverse
method in LINQ? Reverse
Programming Example
Reverse is another sorting method in LINQ but it is slightly different from the OrderBy and ThenBy sorting operator. Reverse method can be used both with OrderBy and ThenBy Operator. Reverse method just prints the list in opposite direction. It doesn’t sort in ascending or descending order, it just reverse the current output. You can understand it using the following programming example.
Reverse Programming Example
using System; using System.Collections.Generic; using System.Linq; namespace LinqTutorial { class ProductStore { public string productName { get; set; } public int productPrice { get; set; } } class Program { static void Main(string[] args) { // Creating List IList<ProductStore> productList = new List<ProductStore>(); productList.Add(new ProductStore { productName = "Hard Disk", productPrice = 1280 }); productList.Add(new ProductStore { productName = "Monitor", productPrice = 3000 }); productList.Add(new ProductStore { productName = "Monitor", productPrice = 3500 }); productList.Add(new ProductStore { productName = "Monitor", productPrice = 2000 }); productList.Add(new ProductStore { productName = "SSD Disk", productPrice = 3500 }); productList.Add(new ProductStore { productName = "RAM", productPrice = 2450 }); productList.Add(new ProductStore { productName = "Processor", productPrice = 7680 }); productList.Add(new ProductStore { productName = "Bluetooth", productPrice = 540 }); productList.Add(new ProductStore { productName = "Keyboard & Mouse", productPrice = 1130 }); var result = productList.OrderBy(p => p.productPrice).Reverse(); foreach (var list in result) { Console.WriteLine("Product Name: {0} | Product Price : {1}", list.productName, list.productPrice); } Console.ReadKey(); } } }
Output:
Product Name: Processor | Product Price : 7680
Product Name: SSD Disk | Product Price : 3500
Product Name: Monitor | Product Price : 3500
Product Name: Monitor | Product Price : 3000
Product Name: RAM | Product Price : 2450
Product Name: Monitor | Product Price : 2000
Product Name: Hard Disk | Product Price : 1280
Product Name: Keyboard & Mouse | Product Price : 1130
Product Name: Bluetooth | Product Price : 540
_
Explanation
You can see that I have sort the list in ascending order based on Productprice using the OrderBy operator and then I used Reverse()
method. The reverse method reversed the current sorted list.
Summary
In this tutorial, I tried to explain Reverse() method in LINQ C# with the help of complete programming example. In the next chapter, you will learn GroupBy in LINQ.