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($"\"{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
*/

另请参阅