let clause (C# Reference)
In a query expression, it's sometimes useful to store the result of a subexpression in order to use it in subsequent clauses. You can do this with the let
keyword, which creates a new range variable and initializes it with the result of the expression you supply. Once initialized with a value, the range variable can't be used to store another value. However, if the range variable holds a queryable type, it can be queried.
Example
In the following example let
is used in two ways:
To create an enumerable type that can itself be queried.
To enable the query to call
ToLower
only one time on the range variableword
. Without usinglet
, you would have to callToLower
in each predicate in thewhere
clause.
class LetSample1
{
static void Main()
{
string[] strings =
[
"A penny saved is a penny earned.",
"The early bird catches the worm.",
"The pen is mightier than the sword."
];
// Split the sentence into an array of words
// and select those whose first letter is a vowel.
var earlyBirdQuery =
from sentence in strings
let words = sentence.Split(' ')
from word in words
let w = word.ToLower()
where w[0] == 'a' || w[0] == 'e'
|| w[0] == 'i' || w[0] == 'o'
|| w[0] == 'u'
select word;
// Execute the query.
foreach (var v in earlyBirdQuery)
{
Console.WriteLine("\"{0}\" starts with a vowel", v);
}
}
}
/* Output:
"A" starts with a vowel
"is" starts with a vowel
"a" starts with a vowel
"earned." starts with a vowel
"early" starts with a vowel
"is" starts with a vowel
*/