ADVANCED LINQ QUERY SYNTAX

The earlier sections described the basic LINQ commands that you might expect to use regularly, but there’s much more to LINQ than these simple queries. The following sections describe some of the more advanced LINQ commands that are less intuitive and that you probably won’t need to use as often.

Join

The Join keyword selects data from multiple data sources matching up corresponding fields. The following pseudo-code shows the Join command’s syntax:

From variable1 In data source1
Join variable2 In data source2
On variable1.field1 Equals variable2.field2

For example, the following query selects objects from the all_customers list. For each object it finds, it also selects objects from the all_orders list where the two records have the same CustId value.

Dim query = From cust As Customer In all_customers
    Join ord In all_orders
    On cust.CustId Equals ord.CustId

A LINQ Join is similar to a SQL join except the On clause only allows you to select objects where fields are equal and the Equals keyword is required.

The following query selects a similar set of objects without using the Join keyword. Here the Where clause makes the link between the all_customers and all_orders lists:

Dim query = From cust As Customer In all_customers, ord In all_orders
    Where cust.CustId = ord.CustId

This is slightly more flexible because the Where clause can make tests that are more complicated than the Join statement’s Equals clause.

The Group Join statement selects data much as ...

Get Visual Basic 2012 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.