如何:在运行时动态指定谓词筛选器(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 类型需要其他 using 指令和引用。有关更多信息,请参见 如何:创建 LINQ 项目。
动态查询示例示例演示使用 LINQ 动态构造查询的另一种方法。