C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Variable: The variable introduced by let (v) is used twice. It is tested (>= 500) and selected into the result.
Tip: Let simplifies code. The new syntax is simpler than trying to compute it over and over again.
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
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 }