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

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

使用例

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

  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);
        }

        // Keep the console window open in debug mode.
        Console.WriteLine("Press any key to exit.");
        Console.ReadKey();
    }
}
/* 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
*/

参照

処理手順

方法 : クエリ式の例外を処理する (C# プログラミング ガイド)

概念

LINQ クエリ式 (C# プログラミング ガイド)

その他の技術情報

C# リファレンス

クエリ キーワード (C# リファレンス)

C# の LINQ の概要