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 7-2. The beauty of this anonymous type is that we don’t really care what type of object is generated for us by the LINQ query, as long as that object has the new property associated with it that we specified, FullName in this case, which it does.

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 7-2 to sort items from the customer List in descending order:

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 (McGraw-Hill/ Professional, 2008). The remaining section of this book takes what you’ve learned here and expands, showing you more samples of LINQ queries. The difference will be that you will be working with SQL Server data instead of in-memory objects.

Page 222
Image 222
Microsoft 9GD00001 manual Using Linq to Sort Collection Results, 199