
Chapter 7: Working with Data | 199 |
only have a FullName property. Notice how the foreach loop uses the FullName property, instead of the FirstName property from Listing
The variable, cust, in the preceding listing is used in two different scopes: the LINQ query and the foreach statement. Although the identifier, cust, is the same, the two usages are separate instances. Although you might not use the same practice in your own code, I wanted to demonstrate this so that you can see that range variables, such as cust, are scoped to the query they are defined in.
Another nuance of the preceding code is that cust, in the foreach loop, is not type Customer. Rather, it is an instance of the anonymous type created by the projection (select clause) of the LINQ query. Therefore, FullName is the only property each anonymous type instance, cust, contains.
Using LINQ to Sort Collection Results
Another common task you’ll want to perform with data is sorting so that you can put objects in a certain order. The following example modifies the example from Listing
C#:
var customers =
from cust in custList
orderby cust.FirstName descending select cust;
VB:
Dim customers =
From cust In custList
Order By cust.FirstName Descending
Select cust
The orderby (Order By in VB) clause specifies the properties to sort on. This example sorts the list by the FirstName property in descending order.
This was a quick taste of what you could do with LINQ, and there is much more. In fact, I wrote an entire book on the subject titled LINQ Programming