在查詢表達式中,儲存子表達式的結果有時很實用,以便在後續子句中使用。 您可以使用 關鍵詞來執行此 let
動作,這會建立新的範圍變數,並以您提供的表達式結果初始化它。 使用值初始化之後,就無法使用範圍變數來儲存另一個值。 不過,如果範圍變數保存可查詢的類型,則可以進行查詢。
範例
在下列範例 let
中,有兩種方式使用:
要建立一種自身可被查詢的可列舉型別。
若要讓查詢在範圍變數
ToLower
上只呼叫word
一次。 如果不使用let
,您就必須在ToLower
子句中的每個述詞中呼叫where
。
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($"\"{v}\" starts with a vowel");
}
}
}
/* 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
*/