共用方式為


篩選資料

更新:2007 年 11 月

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

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

LINQ 篩選作業

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

方法

方法名稱

說明

C# 查詢運算式語法

Visual Basic 查詢運算式語法

詳細資訊

OfType

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

不適用。

不適用。

Enumerable.OfType<TResult>

Queryable.OfType<TResult>

Where

根據述詞函式來選取值。

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

進一步了解如何篩選資料

請參閱

概念

標準查詢運算子概觀

參考

where 子句 (C# 參考)

Where 子句 (Visual Basic)

System.Linq