O'Reilly logo

Programming Visual Basic 2008 by Tim Patrick

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Basic Query Expressions

LINQ expressions are built from query clauses that have the same feel as clauses in SQL statements at the database level. With the exception of the From clause, which must appear first, the other clauses can generally appear in any order within the query.

The From Clause

Every basic LINQ query begins with the From keyword.

Dim bookBag = From bk In Library
ShowResults(bookBag)
' Results --> War and Peace   LT   1424
'             Anna Karenina   LT   976
'             Ben-Hur         LW   544
'             Peter Pan       JB   192

This four-word query is pretty much the shortest LINQ query you can write. I stored the results of the query in the bookBag variable (with its data type inferred by the query), but the query can also be used directly as an expression.

ShowResults(From bk In Library)

The bk variable included in the query is known as a range variable or iteration variable. (You don't have to use "bk"; I just chose that name at random. It's a variable, so give it any name you wish.) This variable provides a way to identify objects and object members from the source data within the query. Since Library is a collection, it wouldn't make sense to say Library.Title when referring to the title of just one book. Instead, you refer to bk.Title.

Personally, I find this variable In source syntax a little indirect. I much prefer the table-alias syntax used in SQL queries.

SELECT * FROM Library AS bk

The SQL AS keyword performs much the same function as the LINQ In keyword. Yet despite my internal tension, the In syntax prevails; ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required