
416
LESSON 37 LINQ to objects
ORDER BY CLAUSES
Often the result of a query is easier to read if you sort the selected values. You can do this by inserting
an order by clause between the where clause and the select clause.
The order by clause begins with the keyword
orderby followed by one or more values separated by
commas that determine how the results are ordered.
Optionally you can follow a value by the keyword
ascending (the default) or descending to determine
whether the results are ordered in ascending (1-2-3 or A-B-C) or descending (3-2-1 or C-B-A) order.
For example, the following query selects
Customers with negative balances and orders them so
those with the smallest (most negative) values come first:
var negativeQuery =
from Customer cust in customers
where cust.Balance < 0
orderby cust.Balance ascending
select cust;
The following version orders the results first by balance and then, if two customers have the same
balance, by last name:
var negativeQuery =
from Customer cust in customers
where cust.Balance < 0
orderby cust.Balance, cust.LastName
select cust;
SELECT CLAUSES
The select clause determines what data is pulled from the data source and stored in the result. All of
the previous examples select the data over which they are ranging. For example, the FindCustomers
example program ranges over an array of
Customer objects and selects certain Customer objects.
Instead of sele ...