C# Let Keyword (Use Variable in Query Expression)

These C# example programs use the let keyword. Let, a part of query expressions, declares and assigns a variable.
Let. This keyword is a part of a query expression. It introduces a variable. We can then reuse the variable elsewhere in the query.
Let, notes. This keyword makes possible certain complex query expressions, and makes other expressions simpler. We add the "using System.Linq" directive to use let.LINQ
First example. This query expression acts upon array elements. It uses the let keyword and computes let by multiplying the element's value by 100.

Variable: The variable introduced by let (v) is used twice. It is tested (>= 500) and selected into the result.

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.

Note: In the query expression above, the variable v is used twice. The "let" clause allows us to avoid duplicate work.

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

Example 2. More than one let can be used in a query. Here we use 2 let-clauses. 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 arguments and return values 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 }
A summary. Let gives you the ability to introduce variables that are stored in memory and can be reused. Like var, a let variable has an implicit (inferred) type.Var
This can be useful for some queries that compute values based on the input data and then reuse those computed values several times. Let can improve performance in this way.
© 2007-2019 Sam Allen. Every person is special and unique. Send bug reports to info@dotnetperls.com.
HomeSearch
Home
Dot Net Perls