linq
  1. linq-sorting-data

Sorting Data in LINQ Query Syntax

LINQ (Language Integrated Query) allows us to query and manipulate collections of data using a query syntax. Sorting data is one of the essential operations we can perform on data collections using LINQ. In this tutorial, we'll learn how to sort data using LINQ query syntax.

Syntax

from variable in collection
orderby property/s descending/ascending
select variable;

Example

Let's say we have a list of products with their name and price, and we want to sort them by price in ascending order.

List<Product> products = new List<Product>()
{
    new Product(){Name="Book", Price=10},
    new Product(){Name="Pen", Price=2},
    new Product(){Name="Bag", Price=20},
    new Product(){Name="Keyboard", Price=50},
    new Product(){Name="Mouse", Price=30},
};

var sortedProducts = from product in products
                     orderby product.Price ascending
                     select product;

foreach (var product in sortedProducts)
{
    Console.WriteLine("Name: {0}, Price: {1}", product.Name, product.Price);
}

Output

Name: Pen, Price: 2
Name: Book, Price: 10
Name: Mouse, Price: 30
Name: Bag, Price: 20
Name: Keyboard, Price: 50

Explanation

In the above syntax, we used the orderby keyword to sort the data in ascending or descending order. The ascending keyword is used to sort the data in ascending order, and descending is used to sort the data in descending order. We also used the select keyword to select the sorted data from the collection and return it in the desired format.

In the example, we sorted the products by their price in ascending order using orderby product.Price ascending. We then selected the sorted data using select product and printed it on the console.

Use

Sorting data is essential when working with large collections of data. Sorting enables us to analyze and identify patterns in the data, which otherwise would be difficult to find.

Important Points

  • We can sort data in ascending or descending order using the orderby keyword and ascending or descending keyword, respectively.
  • We can sort data by multiple properties by chaining orderby clauses.
  • We must specify the sorting order for each property using ascending or descending keyword.

Summary

In this tutorial, we learned how to sort data in LINQ using the query syntax. We saw the syntax to sort data in ascending or descending order and how to select the sorted data. We also saw an example of how to sort a list of products by their price in ascending order. Sorting data is an essential task when working with collections of data, and LINQ provides an easy-to-use syntax to achieve this task.

Published on: