Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C#

Enumerable.ThenBy: practical reference

Enumerable.ThenBy: practical reference: Adds a stable ascending secondary key to an existing IOrderedEnumerable<T>.

Version: .NET LINQ; verified on .NET 10.0.14

Syntax

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

Adds a stable ascending secondary key to an existing IOrderedEnumerable.

Use it after OrderBy or OrderByDescending to break ties from earlier keys.

This contract is unavailable for an unordered source. The whole source remains buffered for sorting.

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

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

Examples

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

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

Result

Z,A,B

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

Sources