Condividi tramite


Clausola let (Riferimento C#)

In un'espressione di query, talvolta è utile archiviare il risultato di una sottoespressione per usarlo nelle clausole successive. A tale scopo, è possibile usare la parola chiave let, che crea una nuova variabile di intervallo e la inizializza con il risultato dell'espressione specificata. Dopo l'inizializzazione con un valore, la variabile di intervallo non può essere usata per archiviare un altro valore. Tuttavia, se la variabile di intervallo contiene un tipo queryabile, può essere interrogata.

Esempio

Nell'esempio seguente let viene usato in due modi:

  1. Per creare un tipo enumerabile che può essere interrogato.

  2. Per consentire alla query di chiamare ToLower una sola volta nella variabile di intervallo word. Senza usare let, è necessario chiamare ToLower in ogni predicato nella 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($"\"{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
*/

Vedere anche