Sorting and more
Other commonly used extension methods are OrderBy
and ThenBy
, used to sort a sequence.
Sorting by a single property using OrderBy
Extension methods can be chained if the previous method returns another sequence, that is, a type that implements the IEnumerable<T>
interface.
Let’s continue working with the current project to explore sorting:
- In the
FilteringUsingWhere
method, append a call toOrderBy
to the end of the existing query, as shown in the following code:var query = names .Where(name => name.Length > 4) .OrderBy(name => name.Length);
Good Practice: Format the LINQ statement so that each extension method call happens on its own line, making it easier to read.
- Run the code, and note that the names are now sorted by the shortest first, as shown in the following output:
Kevin Creed Dwight Angela Michael
To put the longest name first, you would...