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.
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 of OrderBy is basically identical to the other common LINQ methods like Where and Any.