Appendix L. LINQ

This appendix provides syntax summaries for the most useful LINQ methods. For more detailed information, see Chapter 21, "LINQ."

BASIC LINQ QUERY SYNTAX

The following text shows the typical syntax for a LINQ query:

From ... Where ... Order By ... Select ...

The following sections describe these four basic clauses. The sections after those describe some of the other most useful LINQ clauses.

From

The From clause tells where the data comes from and defines the name by which it is known within the LINQ query.

From var1 In data_source1, var2 In data_source2, ...

Examples:

Dim query1 = From cust As Customer In all_customers
Dim query2 = From stu In students, score In TestScores

Usually, if you select data from multiple sources, you will want to use a Where clause to join the results from the sources.

Where

The Where clause applies filters to the records selected by the From clause. The syntax is:

Where conditions

Use comparison operators (>, <, =), logical operators (Not, Or, AndAlso), object methods (ToString, Length), and functions to build complex conditions.

For example, the following query selects student and test score data, matching students to their test scores:

Dim query = From stu In students, score In TestScores
    Where stu.StudentId = score.StudentId

The following example selects only students with last names starting with S:

Dim query = From stu In students, score In TestScores
    Where stu.StudentId = score.StudentId AndAlso
         stu.LastName.ToUpper.StartsWith("S")

Order By

The Order ...

Get Visual Basic® 2010 Programmer's Reference now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.