Skip to content
Tutorials Center
My learning

Topics

Lesson 21 of 36 ยท Collections and LINQ

LINQ Basics

Learn LINQ in VB.NET - From, Where, Select, Order By query syntax, extension methods and lambdas, First, Any, Count, Sum, Average, plus runnable C# stand-ins that use the same operators.

LINQ (Language Integrated Query) lets you ask questions about collections with the same vocabulary you would use for a database: filter, sort, project, group, join. It works on arrays, lists, dictionaries, XML and database tables. VB.NET has especially readable LINQ because queries are built into the language syntax.

The VB compiler is not available on this site, so VB queries are read-only. The runnable blocks are C# stand-ins that call the same System.Linq methods, which VB's Where, Select and Order By compile to.

Two syntaxes, one engine

VB lets you write a query with keywords, or call the extension methods directly. The compiler turns the first into the second.

VB
Dim numbers = {5, 8, 2, 9, 4, 7}

' Query syntax
Dim big = From n In numbers
          Where n > 4
          Order By n Descending
          Select n * 10

' Method syntax (identical result)
Dim big2 = numbers.Where(Function(n) n > 4) _
                  .OrderByDescending(Function(n) n) _
                  .Select(Function(n) n * 10)

Function(n) n > 4 is a lambda: an inline, unnamed function. Query syntax reads like a sentence, method syntax chains well and exposes every operator (operators such as Zip or Distinct have no dedicated keyword in a VB query and are called as methods).

C# Where, OrderBy, Select

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Projecting into new shapes

Select transforms every element. In VB you can build an anonymous type with New With:

VB
Dim cards = From p In products
            Select New With {p.Name, .WithTax = p.Price * 1.2D}
C# Projection into anonymous types

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Filtering and testing

Common filters and tests:

Operator Meaning
Where(pred) keep matching items
Any() / Any(pred) is there at least one?
All(pred) do all match?
Contains(x) is x present?
Distinct() remove duplicates
Take(n), Skip(n) paging
TakeWhile, SkipWhile until a condition fails

Getting single values

First(), Last(), Single() throw when nothing (or, for Single, more than one item) matches. The OrDefault versions return Nothing/0 instead, which is safer when absence is possible.

Aggregates collapse a sequence to a number: Count, Sum, Min, Max, Average, and the general Aggregate.

VB
Dim total = prices.Sum()
Dim avg = prices.Average()
Dim cheapest = products.OrderBy(Function(p) p.Price).FirstOrDefault()
C# Aggregates and safe single-value lookups

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Deferred execution

A LINQ query is not run when you write it. It runs when you enumerate it (For Each, ToList, Count...). Each enumeration runs it again, so the result reflects the source at that moment. Call ToList() or ToArray() when you want a snapshot. The next lesson explores this in depth.

Practical habits

  • Prefer descriptive lambda parameter names (Function(order) order.Total > 100).
  • Put Where before Select and OrderBy to touch fewer items.
  • Use Any() instead of Count() > 0: it stops at the first hit.
  • Use FirstOrDefault and check for Nothing when a match may be missing.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does Function(n) n > 4 represent?

    It is an inline, unnamed function (lambda) used as a predicate.
  2. 2. Which operator is safest when no item might match?

    FirstOrDefault returns a default value instead of throwing.
  3. 3. Why prefer Any() over Count() > 0?

    Any short-circuits; Count may walk the whole sequence.
  4. 4. When does a LINQ query actually run?

    Execution is deferred until the sequence is enumerated or materialized.

Summary

  • LINQ offers query syntax (From/Where/Select) and method syntax; both compile to the same extension methods.
  • Select projects, Where filters, OrderBy sorts, aggregates reduce.
  • First throws on empty; FirstOrDefault does not.
  • Queries are deferred; materialize with ToList for a snapshot.

Next: LINQ Grouping, Joins and Lazy Evaluation