Chapter 7: Working with Data | 197 |
Both the C# and VB examples from Listing
var customers =
from cust in custList
where cust.FirstName.StartsWith("M") select cust;
and the VB LINQ query:
Dim customers =
From cust In custList
Where cust.FirstName.StartsWith("M")
Select cust
The customers variable in the LINQ queries references a new collection that holds the result of running the LINQ query, which contains all of the customers where the first letter of the FirstName property is the letter M. The from clause specifies the range variable that you name, cust is the name I chose, and the collection object to query, custList, was created and populated in the previous line of code. The range variable is what you use to specify parameters of the LINQ query. In the preceding example, we use the where clause to filter the results of the query. This where clause calls the StartsWith method on each FirstName property of the cust range variable to specify the filter.
The select clause specifies that each individual customer object is returned into our new customers collection, which we declared as type var (Dim in VB), which means our customers variable winds up being whatever collection type is returned from our LINQ query. This also means that the resulting customers collection will contain zero or more Customer type instances, depending on the filter we specified and whether our custList contained any Customer objects in the first place as a result of the Select cust portion of the LINQ statement. The select clause for C# queries is required, but the select clause for VB queries is optional and will return the range variable instance if omitted.
What our LINQ statement is essentially saying in English is “Create a new collection object and assign it to our variable customers (we don’t really care what type of object customers turns out to be as long as we can use it later), then go through every object in our previously defined and loaded custList collection, selecting only the ones that have for their FirstName property a string that begins with the letter M, and ignore all the rest, then take the ones that match this filter and stuff them into whatever collection you created for me earlier that you assigned to my variable customers.”