在运行时动态指定谓词筛选器

在某些情况下,在运行时之前你不知道必须将多少个谓词应用于 where 子句中的源元素。 动态指定多个谓词筛选器的方法之一是使用 Contains 方法,如以下示例中所示。 查询将根据执行查询时的 id 值返回不同的结果。

int[] ids = { 111, 114, 112 };

var queryNames =
    from student in students
    where ids.Contains(student.ID)
    select new
    {
        student.LastName,
        student.ID
    };

foreach (var name in queryNames)
{
    Console.WriteLine($"{name.LastName}: {name.ID}");
}

/* Output:
    Garcia: 114
    O'Donnell: 112
    Omelchenko: 111
 */

// Change the ids.
ids = new[] { 122, 117, 120, 115 };

// The query will now return different results
foreach (var name in queryNames)
{
    Console.WriteLine($"{name.LastName}: {name.ID}");
}

/* Output:
    Adams: 120
    Feng: 117
    Garcia: 115
    Tucker: 122
 */

在运行时使用不同的查询

可以使用控制流语句(如 if... elseswitch)在预确定的替代查询之间进行选择。 在下面的示例中,studentQuery 使用其他 where 子句,如果 oddYear 的运行时值为 truefalse

void FilterByYearType(bool oddYear)
{
    IEnumerable<Student> studentQuery;
    if (oddYear)
    {
        studentQuery =
            from student in students
            where student.Year == GradeLevel.FirstYear || student.Year == GradeLevel.ThirdYear
            select student;
    }
    else
    {
        studentQuery =
            from student in students
            where student.Year == GradeLevel.SecondYear || student.Year == GradeLevel.FourthYear
            select student;
    }

    string descr = oddYear ? "odd" : "even";
    Console.WriteLine($"The following students are at an {descr} year level:");
    foreach (Student name in studentQuery)
    {
        Console.WriteLine($"{name.LastName}: {name.ID}");
    }
}

FilterByYearType(true);

/* Output:
    The following students are at an odd year level:
    Fakhouri: 116
    Feng: 117
    Garcia: 115
    Mortensen: 113
    Tucker: 119
    Tucker: 122
 */

FilterByYearType(false);

/* Output:
    The following students are at an even year level:
    Adams: 120
    Garcia: 114
    Garcia: 118
    O'Donnell: 112
    Omelchenko: 111
    Zabokritski: 121
 */

请参阅