Let Clause (Visual Basic)

Computes a value and assigns it to a new variable within the query.

Let variable = expression [, ...]

Parts

  • variable
    Required. An alias that can be used to reference the results of the supplied expression.

  • expression
    Required. An expression that will be evaluated and assigned to the specified variable.

Remarks

The Let clause enables you to compute values for each query result and reference them by using an alias. The alias can be used in other clauses, such as the Where clause. The Let clause enables you to create a query statement that is easier to read because you can specify an alias for an expression clause included in the query and substitute the alias each time the expression clause is used.

You can include any number of variable and expression assignments in the Let clause. Separate each assignment with a comma (,).

Example

The following code example uses the Let clause to compute a 10 percent discount on products.

Dim discountedProducts = From prod In products _
                         Let Discount = prod.UnitPrice * 0.1 _
                         Where Discount >= 50 _
                         Select prod.ProductName, prod.UnitPrice, Discount

ForĀ Each prod In discountedProducts
  Console.WriteLine("Product: {0}, Price: {1}, Discounted Price: {2}", _
                    prod.ProductName, prod.UnitPrice.ToString("$#.00"), _
                    (prod.UnitPrice - prod.Discount).ToString("$#.00"))
Next

See Also

Concepts

Introduction to LINQ in Visual Basic

Reference

Select Clause (Visual Basic)

From Clause (Visual Basic)

Where Clause (Visual Basic)

Other Resources

Queries (Visual Basic)