In this Video, I am going to discuss the LINQ OrderByDescending Method in C# with examples. Please read our previous Video where we discussed the OrderBy Method in C# with some examples. As part of this Video, we are going to discuss the following pointers related to the LINQ OrderByDescending method.
What is LINQ OrderByDescending Method in C#?. The Complete Microsoft .Net 6 LINQ Developer Course 2023 [Videos].
- What is Linq OrderByDescending Method in C#?
- Example of Linq OrderByDescending Method using both Method and Query Syntax.
- How to use Linq OrderByDescending Method with Complex Type in C#?
- How to use the OrderByDescending method along with the Filtering method?
What is Linq OrderByDescending Method in C#?
The LINQ OrderByDescending method in C# is used to sort the data in descending order. The point that you need to remember is, the OrderByDescending method is not going to change the data, it is just changing the order of the data.
Like the OrderBy method, you can also use the OrderByDescending method on any data type such as string, character, float, integer, etc. Let us understand how to use the OrderByDescending method in C# using both query and method syntax.
Working with integer data
In the following example, we have an integer collection. And we need to sort the data in descending order. Let us see how to do this using both query and method syntax.
Working with string data.
In the following example, we have a collection of string data i.e. a collection of names. We want to sort the data in descending order using both method and query syntax. Let us see how we can do this.
LINQ OrderByDescending Method with Complex type in C#:
In order to understand how to work with complex type, we are going to work with the following Student class. So, create a class file with the name Student.cs and then copy and paste the following code in it.
As you can see, we created the above Student class with four simple properties (ID, FirstName, LastName, and Brach). We then created one method (i.e. GetAllStudents) which will return the list of all students.
Sorting the Data in Descending Order
Here, we want to sort the data based on the Branch in descending order.
Linq OrderByDescending with Filtering Operator.
Now we need to fetch only the ETC branch students and then we need to sort the students based on their FirstName in descending order.
Note: The most important point that you need to keep in mind is, you need to use the Where extension method before the OrderByDescending method.