C# – How to sort by multiple fields (Linq)

Use the OrderBy() and ThenBy() Linq methods when you want to sort a list by multiple fields, like this:

using System.Linq;

var sortedTeams = nflTeams.OrderBy(t => t.Conference)
                    .ThenBy(t => t.Division)
                    .ThenBy(t => t.Team);
Code language: C# (cs)

Ascending vs Descending order

By default, OrderBy() and ThenBy() sort in ascending order.

If you want to sort by descending order, use the Descending version of each method.

For example, if I want to sort NFL teams within each division by the number of Super Bowl appearances (and use Super Bowl wins as a tiebreaker), I would use ThenByDescending() like this:

using System.Linq;

var sortedByBestTeamInDivision = nflTeams.OrderBy(t => t.Conference)
		.ThenBy(t => t.Division)
		.ThenByDescending(t => t.SuperBowlWins + t.SuperBowlLosses)
		.ThenByDescending(t => t.SuperBowlWins);
Code language: C# (cs)

This results in the following sort order for the NFL North division:

NFC North - Green Bay Packers have 5 Super Bowl appearances and 4 wins
NFC North - Minnesota Vikings have 4 Super Bowl appearances and 0 wins
NFC North - Chicago Bears have 2 Super Bowl appearances and 1 win
NFC North - Detroit Lions have 0 Super Bowl appearances and 0 wins Code language: plaintext (plaintext)

Leave a Comment