C# LINQ에서 여러 Where 절 활용하기
C#에서는 Where 절을 사용해 컬렉션을 간편하게 필터링할 수 있습니다. 특히 LINQ 쿼리 식 하나에 여러 개의 where 절을 연달아 작성하면, 각 조건이 순차적으로 적용되면서 코드의 의도를 더욱 명확하게 드러낼 수 있습니다.
1. 예제용 컬렉션 준비
먼저 직원(Employee) 객체들로 구성된 리스트를 생성합니다.
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 },
};2. 여러 Where 절로 조건 걸기
이제 where 절 두 개를 연결하여 순위(Rank)가 5보다 크고 10보다 작은 직원만 추출해 보겠습니다.
var res = from e in employee where e.Rank > 5 where e.Rank < 10 select e;
쿼리 실행 시 첫 번째 where 절에서 Rank가 5를 초과하는 요소가 우선 걸러지고, 그 결과 집합에 두 번째 where 절(Rank 10 미만)이 다시 적용되는 구조입니다.
3. 전체 예제 코드
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 },
};
var res = from e in employee
where e.Rank > 5
where e.Rank < 10
select e;
foreach (var emp in res) {
Console.WriteLine("Name: " + emp.EmpName);
Console.WriteLine("Marks: " + 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; }
}4. 실행 결과
Name: Tom Marks: 90
네 명의 직원 중 Rank가 8로 유일하게 조건 범위(5 초과, 10 미만)에 해당하는 Tom만 출력된 것을 확인할 수 있습니다.
참고: 논리 연산자(&&)와의 비교
여러 개의 where 절 대신 하나의 where 절 안에서 && 연산자를 사용해도 동일한 결과를 얻을 수 있습니다.
var res = from e in employee where e.Rank > 5 && e.Rank < 10 select e;
두 방식 모두 같은 결과를 반환하지만, 조건이 많아지거나 복잡해질 경우 where 절을 분리해 작성하면 가독성과 유지보수성이 크게 향상된다는 장점이 있습니다.