C# Linq ThenBy Method

The ThenBy() method in C# LINQ is used to perform a secondary sort on a sequence that has already been ordered using OrderBy(). It allows you to sort by multiple criteria, where OrderBy() defines the primary sort and ThenBy() defines the secondary sort for elements that are equal in the primary sort.

Syntax

Following is the syntax for using ThenBy() method −

IEnumerable<T> result = source.OrderBy(keySelector1).ThenBy(keySelector2);

You can chain multiple ThenBy() methods for additional sort levels −

IEnumerable<T> result = source.OrderBy(key1).ThenBy(key2).ThenBy(key3);

Parameters

  • keySelector − A function that extracts a key from each element for comparison.

  • comparer (optional) − An IComparer<T> to compare keys.

Return Value

Returns an IOrderedEnumerable<T> whose elements are sorted first by the primary key and then by the secondary key.

Using ThenBy() with Strings

The following example sorts strings first by length, then alphabetically for strings with the same length −

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

public class Demo {
    public static void Main() {
        string[] str = { "AAA", "AAAA", "A", "AAAAA", "AAAAAAAAA", "BB", "CCC" };
        
        IEnumerable<string> res = str.OrderBy(s => s.Length).ThenBy(s => s);
        
        Console.WriteLine("Sorted by length, then alphabetically:");
        foreach (string arr in res) {
            Console.WriteLine(arr + " (Length: " + arr.Length + ")");
        }
    }
}

The output of the above code is −

Sorted by length, then alphabetically:
A (Length: 1)
BB (Length: 2)
AAA (Length: 3)
CCC (Length: 3)
AAAA (Length: 4)
AAAAA (Length: 5)
AAAAAAAAA (Length: 9)

Using ThenBy() with Custom Objects

Here's an example using a custom Employee class to demonstrate multi-level sorting −

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

public class Employee {
    public string Name { get; set; }
    public string Department { get; set; }
    public int Age { get; set; }
    
    public override string ToString() {
        return $"{Name}, {Department}, Age: {Age}";
    }
}

public class Program {
    public static void Main() {
        List<Employee> employees = new List<Employee> {
            new Employee { Name = "Alice", Department = "IT", Age = 30 },
            new Employee { Name = "Bob", Department = "HR", Age = 25 },
            new Employee { Name = "Charlie", Department = "IT", Age = 28 },
            new Employee { Name = "Diana", Department = "HR", Age = 25 }
        };
        
        var sortedEmployees = employees
            .OrderBy(emp => emp.Department)
            .ThenBy(emp => emp.Age)
            .ThenBy(emp => emp.Name);
        
        Console.WriteLine("Sorted by Department, then Age, then Name:");
        foreach (var emp in sortedEmployees) {
            Console.WriteLine(emp);
        }
    }
}

The output of the above code is −

Sorted by Department, then Age, then Name:
Bob, HR, Age: 25
Diana, HR, Age: 25
Charlie, IT, Age: 28
Alice, IT, Age: 30

ThenBy() vs ThenByDescending()

Method Sort Order Usage
ThenBy() Ascending Secondary sort in ascending order
ThenByDescending() Descending Secondary sort in descending order

Example with Mixed Sort Orders

using System;
using System.Linq;

public class Program {
    public static void Main() {
        int[] numbers = { 10, 20, 15, 25, 10, 20 };
        
        // Group by tens digit (ascending), then by ones digit (descending)
        var result = numbers
            .OrderBy(n => n / 10)
            .ThenByDescending(n => n % 10);
        
        Console.WriteLine("Numbers sorted by tens (asc), then ones (desc):");
        foreach (int num in result) {
            Console.WriteLine(num);
        }
    }
}

The output of the above code is −

Numbers sorted by tens (asc), then ones (desc):
10
10
25
20
20
15

Conclusion

The ThenBy() method enables multi-level sorting in LINQ by providing secondary sort criteria after the primary OrderBy(). It maintains the order of the primary sort while applying additional sorting rules for equal elements, making it essential for complex data ordering scenarios.

Updated on: 2026-03-17T07:04:35+05:30

385 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements