Overview

A sorting operation orders the elements of a sequence based on one or more attributes.

Methods

MethodDescriptionQuery expression
OrderBy(Descending)Sort values in ascending (descending) orderorderby … and orderby … descending
ThenBy(Descending)Perform a secondary sort in ascending (descending) orderorderby …, … and orderby …, … descending
ReverseReverse the order of the elementsN/A

Primary Ascending Sort

string[] words = { "the", "quick", "brown", "fox", "jumped", "over", "the", "lazy", "dog" };

In query syntax:

var query = from word in words
            orderby word.Length
            select word;

In method syntax:

var query = words.OrderBy(w => w).Select(x => x);

Secondary Sort Ascending

In query syntax:

var query = from word in words
    orderby word.Length, // First, sort by length
            word.Substring(0, 1) // then by the first letter of the word
    select word;

In method syntax:

var query = words.OrderBy(w => w.Length).ThenBy(x => x).Select(y => y);