Sorting and more
Other commonly used extension methods are
ThenBy, used for sorting 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
FilteringUsingWheremethod, append a call to
OrderByto 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, to make it easier to read.
- Run the code and note that the names are now sorted by shortest first, as shown in the following output:
To put the longest name first, you would use
Sorting by a subsequent property using ThenBy
We might want...