LINQ / C#

LINQ OrderByDescending Operator

LINQ OrderByDescending operator sort the elements in a sequence in descending order. You can find LINQ sorting operators list here.

Below is the syntax of OrderByDescending operator.

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

As shown in above syntax, OrderByDescending is an extension method which takes a single element and return property name on which we want to sort the collection in descending order.

We can use OrderByDescending operator in Query Syntax and Method Syntax.

OrderByDescending sort the collection only by a single property. If we want to sort the sequence by multiple properties then we have to use ThenByDescending operator. We will check syntax and usage in below article.

C# OrderByDescending Example in Query Syntax

List<Student> students = new List<Student>();
students.Add(new Student { Id = 1, Name = "Ramesh", Rank = 1, Age = 39 });
students.Add(new Student { Id = 2, Name = "Kapil", Rank = 1, Age = 32 });
students.Add(new Student { Id = 3, Name = "Suresh", Rank = 2, Age = 45 });
students.Add(new Student { Id = 4, Name = "Mahesh", Rank = 2, Age = 39 });

var studentsOrderByRank = from student in students
                            orderby student.Rank descending
                            select student;

Console.WriteLine("Sorted Students:");
foreach (var student in studentsOrderByRank)
{
    Console.WriteLine(student.Name);
}

Result
-------
Sorted Students:
Suresh
Mahesh
Ramesh
Kapil

C# OrderByDescending Example in Method Syntax

var studentsOrderByRank = students.OrderByDescending(w => w.Rank);

Console.WriteLine("Sorted Students:");
foreach (var student in studentsOrderByRank)
{
    Console.WriteLine(student.Name);
}