Share via


篩選資料

篩選作業指的是將結果集限制為只包含符合所指定條件的項目。 同時也稱為選取。

下圖顯示字元序列的篩選結果。 篩選作業的述詞 (Predicate) 指定字元必須是 'A'。

LINQ 篩選作業

下節會列出執行選取的標準查詢運算子方法。

方法

方法名稱

描述

C# 查詢運算式語法

Visual Basic 查詢運算式語法

詳細資訊

OfType

根據是否可以轉換為指定的型別來選取值。

不適用。

不適用。

Enumerable.OfType<TResult>

Queryable.OfType<TResult>

其中

根據述詞函式來選取值。

where

Where

Enumerable.Where

Queryable.Where

查詢運算式語法範例

下列範例使用 where 子句 (在 C# 中) 或 Where 子句 (在 Visual Basic 中),來篩選陣列中具有特定長度的字串。


        Dim words() As String = {"the", "quick", "brown", "fox", "jumps"}

        Dim query = From word In words 
                    Where word.Length = 3 
                    Select word

        Dim sb As New System.Text.StringBuilder()
        For Each str As String In query
            sb.AppendLine(str)
        Next

        ' Display the results.
        MsgBox(sb.ToString())

        ' This code produces the following output:

        ' the
        ' fox


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

請參閱

工作

HOW TO:在執行階段動態指定述詞篩選條件 (C# 程式設計手冊)

HOW TO:使用 LINQ 篩選查詢結果 (Visual Basic)

HOW TO:使用反映查詢組件的中繼資料 (LINQ)

HOW TO:查詢具有指定之屬性或名稱的檔案

HOW TO:依任何字或欄位排序或篩選文字資料 (LINQ)

參考

where 子句 (C# 參考)

Where 子句 (Visual Basic)

System.Linq

概念

標準查詢運算子概觀