Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C#

Enumerable.ThenByDescending: practical reference

Enumerable.ThenByDescending: practical reference: Adds a stable descending secondary key while preserving the priority of earlier keys.

Version: .NET LINQ; verified on .NET 10.0.14

Syntax

source.ThenByDescending(/* overload-specific arguments */)

Adds a stable descending secondary key while preserving the priority of earlier keys.

Use it to break ties descending after the primary OrderBy.

It does not start a new sort; its meaning depends on the preceding IOrderedEnumerable.

An empty source yields an empty result; a null selector causes ArgumentNullException.

The complete program actually uses Enumerable.ThenByDescending; its exact expected stdout is Z,B,A.

Examples

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

var rows = new[] { (Group: 1, Name: "A"), (Group: 1, Name: "B"), (Group: 0, Name: "Z") };
Console.WriteLine(string.Join(",", rows.OrderBy(row => row.Group).ThenByDescending(row => row.Name).Select(row => row.Name)));

Result

Z,B,A

The complete program actually uses `Enumerable.ThenByDescending`; its exact expected stdout is `Z,B,A`.

Sources