INTRODUCTION TO LINQ

The LINQ API provides relatively low-level access to data in various storage formats. Visual Basic provides a higher-level layer above the LINQ API that makes querying data sources easier. This higher-level layer uses query expressions to define the data that should be selected from a data source. These expressions use a SQL-like syntax so they will be familiar to developers who have worked with relational databases.

For example, suppose a program defines a Customer class that provides typical customer properties such as Name, Phone, StreetAddress, AccountBalance, and so forth. Suppose also that the list all_customers holds all of the application’s Customer objects. Then the following expression defines a query that selects customers with negative account balances. The results are ordered by balance in ascending order so customers with the most negative balances (who owe the most) are listed first. (Example program LinqLambda, which is available for download on the book’s website, defines a simple Customer class and performs a similar query.)

Dim overdue_custs =
    From cust In all_customers
    Where cust.AccountBalance < 0
    Order By cust.AccountBalance Ascending
    Select cust.Name, cust.AccountBalance

Behind the scenes, Visual Basic transforms the query expression into calls to the LINQ API and fetches the selected data. The program can then loop through the results as shown in the following code:

For Each cust In overdue_custs Debug.WriteLine(cust.Name & ": " & cust.AccountBalance) ...

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.