let 句 (C# リファレンス)

クエリ式では、後の句で使うため、部分式の結果を保存しておくと便利な場合があります。 let キーワードを使用してこれを行うことができます。これにより新しい範囲変数を作成し、指定した式の結果でそれを初期化します。 値で初期化された範囲変数を、別の値を格納するために使うことはできません。 ただし、範囲変数がクエリ可能型を保持している場合、クエリを実行できます。

次の例で、let は 2 つの方法で使用されます。

  1. それ自体を照会できる列挙可能な型を作成します。

  2. クエリが値変数 word に対して ToLower を 1 回のみ呼び出すことができるようにします。 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
*/

関連項目