Compartir a través de


Cómo: Especificar dinámicamente filtros con predicado en tiempo de ejecución (Guía de programación de C#)

Actualización: noviembre 2007

En algunos casos se desconoce hasta el momento de la ejecución cuántos predicados debe aplicar a los elementos de origen en la cláusula where. Una forma de especificar dinámicamente varios filtros con predicado es utilizar el método Contains, como se muestra en el ejemplo siguiente:

Ejemplo

// 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
*/

Si tiene que elegir entre consultas alternativas predeterminadas, puede utilizar una instrucción switch. En el ejemplo siguiente, studentQuery tiene una cláusula where distinta en función del curso o año especificado en la línea de comandos.

// 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);
    }
}

Compilar el código

Estos ejemplos contienen referencias a objetos definidos en la aplicación de ejemplo del tema Cómo: Realizar una consulta en una colección de objetos (Guía de programación de C#). Para compilar y ejecutar los ejemplos , péguelos en la clase StudentClass de esa aplicación y agregue una llamada al método desde el método Main.

Cuando adapte este método a su propia aplicación, recuerde que LINQ requiere la versión 3.5 de .NET Framework y que el proyecto debe contener una referencia a System.Core.dll y una directiva using para System.Linq. Los tipos LINQ to SQL, LINQ to XML y LINQ to DataSet requieren directivas using y referencias adicionales. Para obtener más información, vea Cómo: Crear un proyecto con LINQ.

El ejemplo Ejemplo Dynamic Query muestra otro enfoque de la construcción de consultas dinámicas con LINQ.

Vea también

Conceptos

Expresiones de consultas con LINQ (Guía de programación de C#)

Referencia

where (Cláusula, Referencia de C#)