let 子句 (C# 參考)

在查詢運算式中,有時它十分適合儲存子運算式的結果,以將它用於後續子句。 您可以使用 let 關鍵字執行這項作業,而此關鍵字會建立新的範圍變數,並使用您提供的運算式結果將它初始化。 使用值初始化之後,就不能使用範圍變數來儲存另一個值。 不過,如果範圍變數保留可查詢類型,則可以進行查詢。

範例

在下列範例中,以兩種方式使用 let

  1. 建立本身可進行查詢的可列舉類型。

  2. 讓查詢只對範圍變數 word 呼叫一次 ToLower。 如果不使用 let,則您需要在 where 子句的每個述詞中呼叫 ToLower

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
*/

另請參閱