ThenByDescending Method

System.Linq
Extension Method for IEnumerable<TSource>

Corresponds to the ThenByDescending extension method within the System.Linq namespace. This method performs a subsequent ordering of elements in a sequence in descending order, according to a key selector function.

Syntax

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

Parameters

Returns

Remarks

The ThenByDescending method is used to perform a secondary sort operation on a sequence that has already been sorted by using OrderBy or OrderByDescending.

If the initial sort operation was not a descending sort, ThenByDescending will apply a descending sort for the secondary sort criterion.

If the sequence is not sorted by OrderBy or OrderByDescending before calling ThenByDescending, the behavior is equivalent to calling OrderByDescending with the specified key selector.

Examples

Example 1: Sorting a list of people by age (descending) then by name (descending)

// Sample data var people = new List<Person> { new Person { Name = "Alice", Age = 30 }, new Person { Name = "Bob", Age = 25 }, new Person { Name = "Charlie", Age = 30 }, new Person { Name = "David", Age = 25 } }; // Sort by Age descending, then by Name descending var sortedPeople = people .OrderByDescending(p => p.Age) .ThenByDescending(p => p.Name) .ToList(); // Output the sorted names and ages foreach (var person in sortedPeople) { // Console.WriteLine($"{person.Name} ({person.Age})"); } // Expected Output: // Charlie (30) // Alice (30) // David (25) // Bob (25)

Example 2: Sorting a list of products by category (ascending) then by price (descending)

var products = new List<Product> { new Product { Name = "Laptop", Category = "Electronics", Price = 1200.00m }, new Product { Name = "Keyboard", Category = "Electronics", Price = 75.00m }, new Product { Name = "Desk", Category = "Furniture", Price = 300.00m }, new Product { Name = "Chair", Category = "Furniture", Price = 150.00m } }; // Sort by Category ascending, then by Price descending var sortedProducts = products .OrderBy(p => p.Category) .ThenByDescending(p => p.Price) .ToList(); // Output the sorted products foreach (var product in sortedProducts) { // Console.WriteLine($$"{product.Name} ({product.Category}, {product.Price:C})"); } // Expected Output: // Laptop (Electronics, $1,200.00) // Keyboard (Electronics, $75.00) // Desk (Furniture, $300.00) // Chair (Furniture, $150.00)