篩選是指限制結果集只包含滿足指定條件的元素的作業。 也稱為 選取 符合指定條件的元素。
這很重要
這些範例會使用 System.Collections.Generic.IEnumerable<T> 資料來源。 根據 System.Linq.IQueryProvider 的資料來源會使用 System.Linq.IQueryable<T> 資料來源和運算式樹。 運算式樹在允許的 C# 語法方面有限制。 此外,每個 IQueryProvider 資料來源 (例如 EF Core) 可能會施加更多限制。 檢查資料來源的文件。
下圖顯示篩選字元序列的結果。 篩選作業的述詞指定字元必須是 『A』。
下表列出執行選取範圍的標準查詢運算符方法:
| 方法名稱 | 說明 | C# 查詢運算式語法 | 詳細資訊 |
|---|---|---|---|
| OfType | 根據是否能轉換為指定型別來選擇值。 | 不適用。 | Enumerable.OfType Queryable.OfType |
| 哪裡 | 選取以述詞函式為基礎的值。 | where |
Enumerable.Where Queryable.Where |
下列範例使用where條件從陣列中篩選出具有特定長度的字串。
備註
您可以在 標準查詢運算子概觀 一文中參閱此區域的常見資料來源。
string[] words = ["the", "quick", "brown", "fox", "jumps"];
IEnumerable<string> query = from word in words
where word.Length == 3
select word;
foreach (string str in query)
{
Console.WriteLine(str);
}
/* This code produces the following output:
the
fox
*/
使用方法語法的對等查詢會顯示在下列程式碼中:
string[] words = ["the", "quick", "brown", "fox", "jumps"];
IEnumerable<string> query =
words.Where(word => word.Length == 3);
foreach (string str in query)
{
Console.WriteLine(str);
}
/* This code produces the following output:
the
fox
*/