Clausola let (Riferimento C#)

In un'espressione di query, talvolta è utile archiviare il risultato di una sottoespressione per usarlo nelle clausole successive. È possibile eseguire questa operazione con la parola chiave let, che crea una nuova variabile di intervallo e la inizializza con il risultato dell'espressione fornita. Dopo l'inizializzazione con un valore, la variabile di intervallo non può essere usata per archiviare un altro valore. Può essere tuttavia sottoposta a query, se contiene un tipo che può essere sottoposto a query.

Esempio

Nell'esempio seguente, let viene usato in due modi:

  1. Per creare un tipo enumerabile che può essere sottoposto a query.

  2. Per consentire alla query di chiamare ToLower solo una volta sulla variabile di intervallo word. Senza usare let, si dovrebbe chiamare ToLower in ogni predicato della clausola 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("\"{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
*/

Vedi anche