Share via


방법: 런타임에 동적으로 조건자 필터 지정(C# 프로그래밍 가이드)

업데이트: 2007년 11월

때로는 런타임 전에 where 절에서 소스 요소에 적용해야 하는 조건자 수를 알 수 없습니다. 다음 예제에서 볼 수 있듯이 동적으로 여러 개의 조건자 필터를 지정하는 한 가지 방법은 Contains 메서드를 사용하는 것입니다.

예제

// To run this sample, first specify some integer values for the command line.
// The numbers 111 through 122 are all valid student IDs.
// In Visual Studio or C# Express, click on Project > Properties > Debug.
// Call the method: QueryByID(args);
static void QueryByID(string[] ids)
{
    var queryNames =
        from student in students
        let i = student.ID.ToString()
        where ids.Contains(i)
        select new { student.LastName, student.ID };

    foreach (var name in queryNames)
    {
        Console.WriteLine("{0}: {1}", name.LastName, name.ID);
    }
}
/* 
 Output (depends on args):
   111 114 118

   Garcia: 114
   Garcia: 118
   Omelchenko: 111
*/

미리 결정된 대체 쿼리 중에서 선택해야 할 경우 switch 문을 사용할 수 있습니다. 다음 예제에서는 명령줄에 등급이 지정되었는지 연도가 지정되었는지에 따라 studentQuery의 where 절이 달라집니다.

// To run this sample, first specify an integer value of 1 to 4 for the command line.
// This number will be converted to a GradeLevel value that specifies which set of students
// to query. In Visual Studio or C# Express, click on Project > Properties > Debug to specify
// command line arguments.
// Call the method: QueryByYear(args[0]);

static void QueryByYear(string level)
{
    GradeLevel year = (GradeLevel)Convert.ToInt32(level);
    IEnumerable<Student> studentQuery = null;
    switch (year)
    {
        case GradeLevel.FirstYear:
            studentQuery = from student in students
                           where student.Year == GradeLevel.FirstYear
                           select student;
            break;
        case GradeLevel.SecondYear:
            studentQuery = from student in students
                           where student.Year == GradeLevel.FirstYear
                           select student;
            break;
        case GradeLevel.ThirdYear:
            studentQuery = from student in students
                           where student.Year == GradeLevel.FirstYear
                           select student;
            break;
        case GradeLevel.FourthYear:
            studentQuery = from student in students
                           where student.Year == GradeLevel.FourthYear
                           select student;
            break;

        default:
            break;
    }
    Console.WriteLine("The following students are at level {0}", year.ToString());
    foreach (Student name in studentQuery)
    {
        Console.WriteLine("{0}: {1}", name.LastName, name.ID);
    }
}

코드 컴파일

예제에는 방법: 개체 컬렉션 쿼리(C# 프로그래밍 가이드)의 샘플 응용 프로그램에 정의된 개체에 대한 참조가 포함되어 있습니다. 이 예제를 컴파일하고 실행하려면 해당 응용 프로그램의 StudentClass 클래스에 예제를 붙여 넣고 이 메서드에 대한 Main 메서드의 호출을 추가해야 합니다.

사용자 고유의 응용 프로그램에 이 메서드를 적용하는 경우 LINQ에서는 .NET Framework 버전 3.5를 필요로 하며 프로젝트에는 System.Core.dll에 대한 참조와 System.Linq에 대한 using 지시문이 포함되어야 합니다. LINQ to SQL, LINQ to XML 및 LINQ to DataSet 형식에는 추가 usings 및 참조가 필요합니다. 자세한 내용은 방법: LINQ 프로젝트 만들기를 참조하십시오.

동적 쿼리 샘플 샘플에서는 LINQ를 사용하여 동적 쿼리를 생성하는 다른 방식을 보여 줍니다.

참고 항목

개념

LINQ 쿼리 식(C# 프로그래밍 가이드)

참조

where 절(C# 참조)