Updated March 30, 2023
Introduction to LINQ Sort
LINQ Sort is used to re-order or re-arrange the given collection of elements into ascending or descending order depends upon the attributes. The sorting operator arranges the sequence of items into ascending or descending order.
In LINQ it includes five sorting operators they are:
- OrderBy
- OrderByDescending
- ThenBy
- ThenByDescending
- Reverse
Syntax of LINQ Sort
Given below are the five LINQ sorting operators with their syntax as follows:
1. OrderBy
var Result_OrderBy = userList.OrderBy(u => u.userName);
2. OrderByDescending
var Result_OrderByDesc = userList.OrderByDescending(u => u.userName);
3. ThenBy
var Result_ThenBy = userList.OrderBy(u => u. userName).ThenBy(u => u.userAge);
4. ThenByDescending
var Result_ThenByDesc = userList.OrderBy(u => u.userName).ThenByDescending(u => u.userAge);
5. Reverse
var Result_Reverse= userList.Reverse();
How does Sort work in LINQ?
The sorting operator is used to re-arrange the given collection of items in ascending or descending order depending on one or more attributes.
The LINQ Sorting operators are of five different types they are as follows:
1. OrderBy
OrderBy sorting is used to sort the values in the sequence based on a particular field in ascending order or descending order; by default, it sorts elements in ascending order.
Example:
Code:
var OrderBy = _products.OrderBy(p => p.productCost);
In the above example, we used the method syntax in OrderBy sort; it sorts the cost of the product it displays the product names based on the Product_Cost wise, by default orderby used ascending order sort.
2. OrderByDescending
OrderByDescending sorts the sequence of elements in descending order. It applies only in the method syntax.
Example:
Code:
var result_OrderByDesc = _products.OrderByDescending(p => p.productCost);
It used the method syntax to sorts elements in descending order; it listed the product details in descending order based on the cost of the product.
3. ThenBy, ThenByDescending
The main purpose of ThenBy and ThenByDescending sorting is for sorting another column along with the prime column. Those both sortings are used for the secondary purpose in LINQ sort; it will be used once the OrderBy and OrderByDescending sort is done; these two are primary sort. ThenBy and ThenByDescending are used after the primary sorting OrderBy and OrderByDescending.
//LINQ SORT – ThenBy Method Syntax
var result_ThenBy = _products.OrderBy(p => p.productName).ThenBy(p => p.productCost);
//LINQ SORT – ThenByDescending
var result_ThenByDesc = _products.OrderBy(a => a.productName).ThenByDescending(a => a.productCost).ToList();
It applies extra additional sorting on columns. This sorting will not be applicable in the query syntax; it can be used only in method syntax.
4. Reverse
The final sort is reverse sorting in LINQ; the main purpose of this sort is to display the sequence of the list in the opposite direction. Thus, it can be used in both OrderBy and ThenBy operators, respectively. It does not sort in ascending or descending order; it only displays from the current position in reverse order.
Example:
Code:
var result_Reverse = _products.OrderBy(p => p.productName).Reverse();
Examples of LINQ Sort
LINQ Sorting operator arranges the sequence of items into ascending or descending order. In LINQ it includes five sorting operators.
Let’s see the five sorting operators with examples programmatically.
Example #1
Code:
using System;
using System.Collections.Generic;
using System.Linq;
namespace Console_LINQSort
{
class ProductClass
{
public string productName { get; set; }
public int productCost { get; set; }
}
class Program
{
static void Main(string[] args)
{
// Creating the product details List
IList<ProductClass> _products = new List<ProductClass>();
_products.Add(new ProductClass { productName = "Speakers", productCost = 2880 }); _products.Add(new ProductClass { productName = "Graphics-Card", productCost = 3000 });
_products.Add(new ProductClass { productName = "Disk-Drive", productCost = 4000 });
_products.Add(new ProductClass { productName = "KeyBoard", productCost = 1540 });
_products.Add(new ProductClass { productName = "Processor", productCost = 7590 });
_products.Add(new ProductClass { productName = "Monitor", productCost = 3250 });
_products.Add(new ProductClass { productName = "Pendrive", productCost = 475 });
_products.Add(new ProductClass { productName = "Pendrive", productCost = 650 });
_products.Add(new ProductClass { productName = "Pendrive", productCost = 870 });
_products.Add(new ProductClass { productName = "Desktop-Table", productCost = 1350 });
//LINQ SORT- OrderBy Method Syntax -default sort is ascending
var result_OrderBy = _products.OrderBy(p => p.productCost);
//LINQ SORT- OrderByDesc Method Syntax
var result_OrderByDesc = _products.OrderByDescending(p => p.productCost);
//LINQ SORT - ThenBy Method Syntax
var result_ThenBy = _products.OrderBy(p => p.productName).ThenBy(p => p.productCost);
//LINQ SORT - ThenByDescending
var result_ThenByDesc = _products.OrderBy(a => a.productName).ThenByDescending(a => a.productCost).ToList();
Console.WriteLine("\n\tUsing LINQ - SORTING \n");
//Order_By
Console.WriteLine("1. OrderBy\n");
Console.WriteLine("\tProduct-Details \n");
Console.WriteLine("\tProduct-Price\t Product-Name\n");
Console.WriteLine("\t--------------\t ------------- \n");
foreach (var val in result_OrderBy)
{
Console.WriteLine("\t {0}\t\t {1}", val.productCost, val.productName);
}
Console.WriteLine("\n\t--------------\t ------------- \n");
//Order_By_Desc
Console.WriteLine("2. OrderBy_Descending\n");
Console.WriteLine("\tProduct-Details \n");
Console.WriteLine("\tProduct-Price\t Product-Name\n");
Console.WriteLine("\t--------------\t ------------- \n");
foreach (var val in result_OrderByDesc)
{
Console.WriteLine("\t {0}\t\t {1}", val.productCost, val.productName);
}
Console.WriteLine("\n\t--------------\t ------------- \n");
//Then_By
Console.WriteLine("3. ThenBy\n");
Console.WriteLine("\tProduct-Details \n");
Console.WriteLine("\tProduct-Price\t Product-Name\n");
Console.WriteLine("\t--------------\t ------------- \n");
var result = _products.OrderBy(a => a.productName).ThenBy(a => a.productCost).ToList();
foreach (var val in result)
{
Console.WriteLine("\t {0}\t\t {1}", val.productName, val.productCost);
}
Console.WriteLine("\n\t--------------\t ------------- \n");
//ThenBy_Descending
Console.WriteLine("4. ThenBy Descending\n");
Console.WriteLine("\tProduct-Details \n");
Console.WriteLine("\tProduct-Price\t Product-Name\n");
Console.WriteLine("\t--------------\t ------------- \n");
foreach (var val in result_ThenByDesc)
{
Console.WriteLine("\t {0}\t\t {1}", val.productName, val.productCost);
}
Console.WriteLine("\n\t--------------\t ------------- \n");
Console.ReadKey();
}
}
}
Output:
Example #2
The main purpose of this sort is to display the sequence of the list in the opposite direction. Thus, it can be used in both OrderBy and ThenBy operators. It does not sort in ascending or descending order; it only displays from the current position in reverse order.
Code:
using System;
using System.Collections.Generic;
using System.Linq;
namespace Console_LINQSort
{
class ProductClass
{
public string productName { get; set; }
public int productCost { get; set; }
}
class Program
{
static void Main(string[] args)
{
// Creating the product details List
IList<ProductClass> _products = new List<ProductClass>();
_products.Add(new ProductClass { productName = "Speakers", productCost = 2880 });
_products.Add(new ProductClass { productName = "Graphics-Card", productCost = 3000 });
_products.Add(new ProductClass { productName = "Disk-Drive", productCost = 4000 });
_products.Add(new ProductClass { productName = "KeyBoard", productCost = 1540 });
_products.Add(new ProductClass { productName = "Processor", productCost = 7590 });
_products.Add(new ProductClass { productName = "Monitor", productCost = 3250 });
_products.Add(new ProductClass { productName = "Pendrive", productCost = 475 });
_products.Add(new ProductClass { productName = "Pendrive", productCost = 650 });
_products.Add(new ProductClass { productName = "Pendrive", productCost = 870 });
_products.Add(new ProductClass { productName = "Desktop-Table", productCost = 1350 });
var result_Reverse = _products.OrderBy(p => p.productName).Reverse();
Console.WriteLine("\n\tUsing LINQ - Sorting \n");
//Reverse Sorting
Console.WriteLine("Reverse Sort\n");
Console.WriteLine("\tProduct-Details \n");
Console.WriteLine("\tProduct-Price\t Product-Name\n");
Console.WriteLine("\t--------------\t ------------- \n");
foreach (var val in result_Reverse)
{
Console.WriteLine("\t {0}\t\t {1}", val.productName, val.productCost);
}
Console.WriteLine("\n\t--------------\t ------------- \n");
Console.ReadKey();
}
}
}
It just sorts the elements in reversed order from the current sorted list of elements; in this program, we just sort in ascending order based on the cost of the product by using orderby and then Reverse method is used it just prints the reverse order of the current list, it’s an opposite direction of the list.
Output:
Conclusion
In this article, we have seen the usage of different types of Sorting Operators in LINQ. By using those sorting operators OrderBy, OrderByDescending, ThenBy, ThenByDescending and Reverse, we can easily sort our data in our desired way as per our requirement.
Recommended Articles
This is a guide to LINQ Sort. Here we discuss the introduction, how sort works in LINQ? and examples for better understanding. You may also have a look at the following articles to learn more –