C# – How to sort by multiple fields

Use OrderBy() and ThenBy() when you want to sort by multiple fields, like this:

var sortedTeams = nflTeams.OrderBy(t => t.Conference)
                    .ThenBy(t => t.Division)
                    .ThenBy(t => t.Team);

Note: These are Linq extension methods, so make sure to add a reference to System.Linq.

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:

var sortedByBestTeamInDivision = nflTeams.OrderBy(t => t.Conference)
		.ThenBy(t => t.Division)
		.ThenByDescending(t => t.SuperBowlWins + t.SuperBowlLosses)
		.ThenByDescending(t => t.SuperBowlWins);

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

Leave a Comment