篩選資料 (C#)Filtering Data (C#)

篩選指的是將結果集限制為只包含符合指定條件之元素的作業,Filtering refers to the operation of restricting the result set to contain only those elements that satisfy a specified condition. 也稱為選取。It is also known as selection.

下圖顯示字元序列的篩選結果。The following illustration shows the results of filtering a sequence of characters. 篩選作業的述詞指定字元必須為 'A'。The predicate for the filtering operation specifies that the character must be 'A'.

顯示 LINQ 篩選作業的圖表

執行選取的標準查詢運算子方法詳列於下一節。The standard query operator methods that perform selection are listed in the following section.

方法Methods

方法名稱Method Name 說明Description C# 查詢運算式語法C# Query Expression Syntax 更多資訊More Information
OfTypeOfType 根據可轉換為所指定類型的能力來選取值。Selects values, depending on their ability to be cast to a specified type. 不適用。Not applicable. Enumerable.OfType

Queryable.OfType
WhereWhere 根據述詞函式來選取值。Selects values that are based on a predicate function. where Enumerable.Where

Queryable.Where

查詢運算式語法範例Query Expression Syntax Example

下列範例使用 where 子句從陣列篩選出具有特定長度的字串。The following example uses the where clause to filter from an array those strings that have a specific length.

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  
*/  

另請參閱See also