let 절(C# 참조)

업데이트: 2007년 11월

쿼리 식에서는 후속 절에서 쿼리 식을 사용하기 위해 부분식의 결과를 저장하는 것이 좋습니다. 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("\"{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 시작