使用 LINQ 篩選 C# 中的資料
篩選指的是將結果集限制為只包含符合指定條件之元素的作業, 這也稱為選取符合指定條件的元素。
下圖顯示字元序列的篩選結果。 篩選作業的述詞指定字元必須為 '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
*/
另請參閱
意見反應
https://aka.ms/ContentUserFeedback。
即將登場:在 2024 年,我們將逐步淘汰 GitHub 問題作為內容的意見反應機制,並將它取代為新的意見反應系統。 如需詳細資訊,請參閱:提交並檢視相關的意見反應