TheDeveloperBlog.com


C# Let 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, and makes other expressions simpler.

Based on:

.NET 4.5


Example. This query expression acts upon array elements. It uses the let keyword and computes let by multiplying the element's value by 100. The variable introduced by let (v) is used twice. It is tested (>= 500) and selected into the result.

Multiply
C# program that uses let keyword

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


Discussion. 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. In the query expression above, the variable v is used twice.

Tip: Let simplifies code. The new syntax is simpler than trying to compute it over and over again.


Example 2. More than one let variable can be used in a query. Here we use two let-clauses to store values. We store in "v" the result of Analyze on an array element, and in "x" the result of Analyze on that value.

Note: Let makes sense here. We reuse the value of "v" in the query, so we do not need to compute it twice.

Result: This program generates a collection of the argument-return value pairs of the Analyze() method.

C# program that uses two let clauses

using System;
using System.Linq;

class Program
{
    static int Analyze(int value)
    {
	// Return a value for each argument.
	switch (value)
	{
	    case 0:
		return 1;
	    case 1:
		return 2;
	    case 2:
	    default:
		return 3;
	}
    }

    static void Main()
    {
	int[] array = { 0, 1, 2 };

	// Build IEnumerable of Analyze arguments and its return values.
	var result = from element in array
		     let v = Analyze(element)
		     let x = Analyze(v)
		     select new { v, x };

	// This prints argument, return value pairs.
	foreach (var element in result)
	{
	    Console.WriteLine(element);
	}
    }
}

Output

{ v = 1, x = 2 }
{ v = 2, x = 3 }
{ v = 3, x = 3 }


Summary. 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.