HOW TO:在執行階段動態指定述詞篩選條件 (C# 程式設計手冊)
更新:2007 年 11 月
在某些情況下,在執行階段之前您不知道必須將多少述詞 (Predicate) 套用至 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);
}
}
編譯程式碼
這些範例內含在 HOW TO:查詢物件集合 (C# 程式設計手冊) 中的範例應用程式中所定義的物件之參考。若要編譯和執行這些範例,請將範例貼至該應用程式中的 StudentClass 類別,並加入來自 Main 方法的方法呼叫。
在配合應用程式調整這個方法時,請注意,LINQ 需要 3.5 版的 .NET Framework,而且專案必須包含 System.Core.dll 的參考,以及 System.Linq 的 using 指示詞。LINQ to SQL、LINQ to XML 和 LINQ to DataSet 型別則需要額外的 Using 和參考。如需詳細資訊,請參閱HOW TO:建立 LINQ 專案。
動態查詢範例範例將說明另一個使用 LINQ 建構動態查詢的方法。