Home
C#
let Keyword
This page was last reviewed on Feb 14, 2022.
Dot Net Perls
Let. This C# 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.
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.
Detail The variable introduced by let (v) is used twice. It is tested (against 500) and selected into the result.
Tip Let simplifies code. The new syntax is simpler than trying to compute it over and over again.
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); } }
500 700 900
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.
switch
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.
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); } } }
{ v = 1, x = 2 } { v = 2, x = 3 } { v = 3, x = 3 }
A 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.
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.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Feb 14, 2022 (edit).
Home
Changes
© 2007-2024 Sam Allen.