into

into (C# 참조)

쿼리에서 결과를 잠시 담아둘 임시 식별자가 필요할 때가 있어요. into라는 컨텍스트 키워드(contextual keyword)가 바로 그 역할을 해요. group 절이나 join 절, select 절의 결과를 임시 식별자에 저장하면, 그 식별자를 다음 쿼리 명령의 발전기(generator) 처럼 사용할 수 있어요. 이렇게 만든 새 식별자를 group 절이나 select 절에서 쓰면 이걸 연속(continuation) 이라고 부르기도 해요.

다음 예시를 보면서 이야기해 볼게요. intofruitGroup이라는 임시 식별자를 만드는 코드인데, 이 식별자의 유추된 타입은 IGrouping이에요. 이 식별자를 활용하면 각 그룹에 xref:System.Linq.Enumerable.Count* 메서드를 호출해서, 단어가 두 개 이상 들어 있는 그룹만 골라낼 수 있어요.

namespace IntoClause;

class IntoSample1
{
    static void Main()
    {

        // Create a data source.
        string[] words = ["apples", "blueberries", "oranges", "bananas", "apricots"];

        // Create the query.
        var wordGroups1 =
            from w in words
            group w by w[0] into fruitGroup
            where fruitGroup.Count() >= 2
            select new { FirstLetter = fruitGroup.Key, Words = fruitGroup.Count() };

        // Execute the query. Note that we only iterate over the groups,
        // not the items in each group
        foreach (var item in wordGroups1)
        {
            Console.WriteLine($" {item.FirstLetter} has {item.Words} elements.");
        }
    }
}
/* Output:
   a has 2 elements.
   b has 2 elements.
*/

여기서 흐름을 짚어 볼게요. group ... by ... into fruitGroup에서 그룹핑 결과가 fruitGroup에 담기고, 그다음 where fruitGroup.Count() >= 2처럼 각 그룹에 추가 쿼리 연산을 걸 수 있어요. 그래서 group 절에서 into각 그룹에 추가 작업을 더 하고 싶을 때만 쓰면 됩니다. 언제 필요한지는 group 절 문서에서 더 자세히 볼 수 있어요.

join 절에서 into를 쓰는 예시가 궁금하다면 join 절 문서를 확인해 보세요.

더 알아보기