System.Linq.Queryable

OrderByDescending<TSource>(IQueryable<TSource>, Expression<Func<TSource, TKey>>)

public static IOrderedQueryable<TSource> OrderByDescending<TSource, TKey>(
this IQueryable<TSource> source,
Expression<Func<TSource, TKey>> keySelector
)

Corresponds to the OrderByDescending operator. Sorts the elements of a sequence in descending order according to a key.

Parameters

Name Type Description
source IQueryable<TSource> An IQueryable<TSource> whose elements to order.
keySelector Expression<Func<TSource, TKey>> A function to extract a comparison key from each element.

Type Parameters

Name Description
TSource The type of the elements of source.
TKey The type of the key by which to order the elements.

Remarks

The OrderByDescending method performs a deferred execution. The query that this method returns must be executed by calling an appropriate method of IQueryable<T> or by using IEnumerable<T> directly in some cases.

This method supports the following LINQ provider implementations:

  • The LINQ to SQL provider.
  • The LINQ to Objects provider.

The OrderByDescending method performs a stable sort. For more information, see OrderBy.

Example

The following code example demonstrates how to use the OrderByDescending method to sort a list of numbers in descending order.


using System;
using System.Linq;
using System.Collections.Generic;

public class Example
{
    public static void Main(string[] args)
    {
        // Sample list of numbers
        List<int> numbers = new List<int>() { 5, 2, 8, 1, 9, 4 };

        // Sort the numbers in descending order
        var sortedNumbers = numbers.AsQueryable().OrderByDescending(n => n).ToList();

        // Print the sorted numbers
        Console.WriteLine("Numbers sorted in descending order:");
        foreach (var number in sortedNumbers)
        {
            Console.Write(number + " ");
        }
        // Output: 9 8 5 4 2 1
    }
}
                

See Also