C# LINQ — “OrderBy”

LINQ (Language-Integrated Query) is a set of integrated C# capabilities which allow queries against data.

Today’s Objective: Reorder the elements in a data collection based on sorting conditions using the LINQ OrderBy method.

The OrderBy Method:

The OrderBy method of LINQ allows data collections such as arrays, Lists, and IEnumerables to be reordered based on conditions set inside the OrderBy method call.

Microsoft Documentation

An Example:

In this example, the grades are first sorted into a new collection which only contains the grades that are above 69 (“passing” grades). Then the elements of that new collection are reordered into ascending order, from lowest to highest. OrderBy sorts into ascending order by default, but in this case I want it in descending order, so I use the Reverse() method to invert the sorted order.

An alternative to “OrderBy().Reverse()” is simply to use “OrderByDescending()”. This combines the 2 methods and sorts the collection into descending order.

The Syntax:

The syntax of OrderBy is basically identical to the other common LINQ methods like Where and Any.



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Vincent Taylor

Vincent Taylor

Unity game developer / C# Programmer / Gamer. Australian (Tasmanian) indie games developer for 10+ years. Currently looking for games industry employment.