To use multiple order by statements in your LINQ query you can use the OrderBy Method combined with multiple ThenBy Method’s.

Example

so let’s create a sample class

sample class track

and fill a List of Track with Track items

Fill tracks into List of Tracks

the items are printed without sorting in the following order

The printed Tracks without sorting them

now let’s sort the List of Tracks first by AlbumId Ascending and ThenBy Title Descending.

var sortedTracksQuerySyntax = (from track in tracks orderby track.AlbumId ascending, track.Title descending select track);
var sortedTracksAggregateFunctions = tracks.OrderBy(track => track.AlbumId).ThenByDescending(track => track.Title);

which will produce the following result

The sorted List of Tracks

Tip

you can use as much ThenBy Statements as you need, example:

var sortedTracksAggregateFunctions = tracks.OrderBy(track => track.AlbumId).ThenByDescending(track => track.Title).ThenBy(track => track.AlbumTitle).ThenByDescending(track => track.Length).ThenBy(track => track.Year);

more informations can be found at the MSDN OrderBy Method, ThenBy Method’s, LINQ, 101 LINQ Samples

Leave a Reply