C# Let

Let contextual keyword

Let is a part of a query expression. It introduces a variable. We can then reuse the variable elsewhere in the query. This makes possible certain complex query expressions.

Example

This program uses a query expression that acts upon each element in the array instance. It uses the let keyword and computes let by multiplying the element's value by 100. Then, the variable introduced by let (v) is used twice: it is tested (>= 500), and finally selected into the result.

Program that uses let keyword [C#]

using System;
using System.Linq;

class Program
{
    static void Main()
    {
	int[] array = { 1, 3, 5, 7, 9 };

	var result = from element in array
		     let v = element * 100
		     where v >= 500
		     select v;

	foreach (var element in result)
	    Console.WriteLine(element);
    }
}

Output

500
700
900
Programming tip

When to use let. You only need to use the let keyword if you are introducing a new variable into the query expression that must be computed and also reused. As you can see in the query expression above, the variable v is used twice. This is simpler than trying to compute it over and over again.

Summary

The C# programming language

We looked at an example of the let keyword in the query sub-language in the C# language. Let gives you the ability to introduce variables that are stored in memory and can be reused. This can be useful for some queries that compute values based on the input data and then reuse those computed values several times.

LINQ Examples
.NET