LINQ FUNCTIONS

LINQ provides several functions (implemented as extension methods) that are not supported by Visual Basic’s LINQ syntax. Though you cannot use these in LINQ queries, you can apply them to the results of queries to perform useful operations.

For example, the following code defines a query that looks for customers named Rod Stephens. It then applies the FirstOrDefault extension method to the query to return either the first object selected by the query or Nothing if the query selects no objects.

Dim rod_query = From cust In all_customers
    Where cust.LastName = "Stephens" AndAlso cust.FirstName = "Rod"
Dim rod As Person = rod_query.FirstOrDefault()

The following list describes some of the more useful of these extension methods:

  • Aggregate — Uses a function specified by the code to calculate a custom aggregate.
  • Concat — Concatenates two sequences into a new sequence.
  • Contains — Determines whether the result contains a specific value.
  • DefaultIfEmpty — If the query’s result is not empty, returns the result. If the result is empty, returns an IEnumerable containing a default value. Optionally can also specify the default value (for example, a new object rather than Nothing) to use if the query’s result is empty.
  • ElementAt — Returns an element at a specific position in the query’s result. If there is no element at that position, it throws an exception.
  • ElementAtOrDefault — Returns an element at a specific position in the query’s result. If there is no element at that position, ...

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.