Linq OrderByDescending Method in C#

In C#, LINQ (Language-Integrated Query) provides a range of methods to sort data, including the OrderByDescending method. This method sorts the elements in a sequence in descending order, based on a specified key. In this lesson, we will learn how to use the OrderByDescending method in C#.

Syntax: The syntax of the OrderByDescending method is as follows:

public static IOrderedEnumerable<TSource> OrderByDescending<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector)

Here, source represents the sequence of elements to be sorted in descending order, and keySelector specifies the key to sort the elements.

Example:

Let’s consider an example where we have a list of employees with their names and salaries, and we want to sort them in descending order based on their salaries.

class Employee
{
    public string Name { get; set; }
    public int Salary { get; set; }
}

List<Employee> employees = new List<Employee>()
{
    new Employee { Name = "John", Salary = 5000 },
    new Employee { Name = "Alice", Salary = 6000 },
    new Employee { Name = "Bob", Salary = 4000 },
    new Employee { Name = "Jane", Salary = 7000 }
};

var sortedEmployees = employees.OrderByDescending(emp => emp.Salary);

foreach (var emp in sortedEmployees)
{
    Console.WriteLine($"{emp.Name} - {emp.Salary}");
}

Output:

Jane - 7000
Alice - 6000
John - 5000
Bob - 4000

In this example, we have defined a class Employee with Name and Salary properties. We have created a list of employees with their names and salaries. Using the OrderByDescending method, we have sorted the employees in descending order based on their salaries.

Conclusion: The OrderByDescending method in LINQ is a useful method to sort data in descending order based on a specified key. It provides a convenient and efficient way to sort sequences of data in C#.