Computer >> 컴퓨터 >  >> 프로그래밍 >> C#

C#의 into 키워드 완벽 가이드: LINQ 쿼리 절에서 into 연산자 활용하기

C#의 LINQ에서 into 연산자는 select 절의 쿼리 결과를 새로운 범위 변수에 저장하여 이후 추가 필터링이나 연산을 수행할 수 있게 해주는 강력한 기능입니다. 하나의 쿼리 표현식 안에서 중간 결과를 계속 이어받아 처리할 때 유용하게 사용됩니다.

예제 데이터 준비

먼저 직원 정보가 담긴 리스트를 준비하겠습니다.

IList<Employee> employee = new List<Employee>() {
    new Employee() { EmpID = 1, EmpName = "Tom", EmpMarks = 90, Rank = 8 },
    new Employee() { EmpID = 2, EmpName = "Anne", EmpMarks = 60, Rank = 21 },
    new Employee() { EmpID = 3, EmpName = "Jack", EmpMarks = 76, Rank = 18 },
    new Employee() { EmpID = 4, EmpName = "Amy", EmpMarks = 67, Rank = 20 },
};

into 연산자를 사용한 쿼리 작성

이제 이름이 'k'로 끝나면서 순위(Rank)가 5보다 크고 20보다 작은 직원을 조회해 보겠습니다. 첫 번째 where 조건으로 순위를 필터링한 뒤, select 절에서 into 연산자로 결과를 name이라는 새 범위 변수에 저장하고, 다시 한 번 이름 조건으로 필터링합니다.

var res = from e in employee
          where e.Rank > 5
          where e.Rank < 20
          select e
          into name
          where name.EmpName.EndsWith("k")
          select name;

전체 코드 예제

지금까지 설명한 내용을 하나의 완성된 프로그램으로 정리하면 다음과 같습니다.

using System;
using System.Linq;
using System.Collections.Generic;

public class Demo {
    public static void Main() {
        IList<Employee> employee = new List<Employee>() {
            new Employee() { EmpID = 1, EmpName = "Tom", EmpMarks = 90, Rank = 8 },
            new Employee() { EmpID = 2, EmpName = "Anne", EmpMarks = 60, Rank = 21 },
            new Employee() { EmpID = 3, EmpName = "Jack", EmpMarks = 76, Rank = 18 },
            new Employee() { EmpID = 4, EmpName = "Amy", EmpMarks = 67, Rank = 20 },
        };

        // 이름이 k로 끝나고 순위가 5보다 크며 20보다 작은 직원 조회
        var res = from e in employee
                  where e.Rank > 5
                  where e.Rank < 20
                  select e
                  into name
                  where name.EmpName.EndsWith("k")
                  select name;

        foreach (var emp in res) {
            Console.WriteLine("이름: " + emp.EmpName);
            Console.WriteLine("점수: " + emp.EmpMarks);
        }
    }
}

public class Employee {
    public int EmpID { get; set; }
    public string EmpName { get; set; }
    public int EmpMarks { get; set; }
    public int Rank { get; set; }
}

실행 결과

프로그램을 실행하면 조건(순위 6~19 사이, 이름이 'k'로 끝남)을 만족하는 직원만 출력됩니다.

이름: Jack
점수: 76

정리

into 연산자는 select 절의 결과를 새로운 범위 변수로 전달하여 쿼리를 단계적으로 확장할 수 있게 해줍니다. 복잡한 조건의 데이터를 여러 단계로 나누어 처리해야 할 때 코드의 가독성과 유지보수성을 크게 높여주므로, LINQ를 활용한 C# 개발에서 꼭 익혀두면 좋은 문법입니다.