Using LINQ OrderBy to Sort Data
linq
26 Articles
In this article, let's learn about how to use OrderBy
in LINQ
in .NET.
Note: If you have not done so already, I recommend you read the article on Using LINQ to Select and Project Data.
Table of Contents
- Introduction
- TLDR
- Single Property
- Single Property in Descending
- Multiple Properties
- Multiple Properties in Descending
- Summary
Introduction
We can use LINQ OrderBy
to sort data within collections. ThenBy
can be chained to sort by more than one
column. Sorting can be done in both ascending and descending order. Default sort is done in ascending order.
LINQ has the following sort methods which can be chained and used in any combination.
- OrderBy()
- ThenBy()
- OrderByDescending()
- ThenByDescending()
TLDR
OrderBy Single Property
The following example shows how to sort Product
class by Name in ascending order.
Code Sample - LINQ OrderBy Single Property
OrderBy Single Property in Descending
The following example shows how to sort Product
class by Name in descending order.
Code Sample - LINQ OrderBy Single Property in Descending
OrderBy Multiple Properties
The following example shows how to sort Product
class with more than one property in ascending order.
Code Sample - LINQ OrderBy Multiple Properties
OrderBy Multiple Properties in Descending
The following example shows how to sort Product
class with more than one property in descending order.
Code Sample - LINQ OrderBy Multiple Properties in Descending
Demo - LINQ OrderBy Clause Demo
Let's try LINQ OrderBy
- We have
Product
class with following properties -Id, Name, Color, Price, Size
- Enter the column names you would like to sort. To sort in descending order enter column name and leave a space and enter desc. Example,
Name desc
- Click on Order By Button
- Click on reset to try other combination
Id | Name | Color | Price | Size |
---|---|---|---|---|
1 | Shirt | Black | 1000 | 18 |
2 | Shirt | Red | 1500 | 28 |
3 | Shirt | Black | 2000 | 38 |
4 | Shirt | Red | 2500 | 48 |
5 | Shirt | Brown | 3000 | 58 |
6 | Shirt | White | 3500 | 68 |
Summary
In this article we learn't how to sort data within collection using LINQ. We also learn't how to sort with multiple fields. All these can be used with any
IEnumerable
or IQueryable
types.