共用方式為


分割資料 (Visual Basic)

LINQ 中的分割是指將輸入序列分成兩個區段的作業,不用重新排列項目,然後傳回其中一個區段。

下圖顯示字元序列三種不同分割作業的結果。 第一項作業會傳回序列中的前三個項目。 第二項作業會略過前三個項目,傳回其餘項目。 第三個作業會略過序列中的前兩個項目,傳回接下來的三個元項目。

Illustration that shows three LINQ partitioning operations.

分割序列的標準查詢運算子方法詳列於下一節。

操作員

運算子名稱 描述 Visual Basic 查詢運算式語法 相關資訊
跳過 略過項目直至序列中指定的位置為止。 Skip Enumerable.Skip

Queryable.Skip
SkipWhile 根據述詞函式跳過項目,直到不符合條件的項目為止。 Skip While Enumerable.SkipWhile

Queryable.SkipWhile
Take 採用序列中最多到指定位置為止的項目。 Take Enumerable.Take

Queryable.Take
TakeWhile 根據述詞函式採用項目,直到不符合條件的項目為止。 Take While Enumerable.TakeWhile

Queryable.TakeWhile
區塊 將序列的元素分割為指定大小上限的區塊。 Enumerable.Chunk
Queryable.Chunk

查詢運算式語法範例

跳過

下列程式碼範例使用 Visual Basic 中的 Skip 子句,先略過字串陣列中的前四個字串,再傳回陣列中的其餘字串。


Dim words = {"an", "apple", "a", "day", "keeps", "the", "doctor", "away"}

Dim query = From word In words
            Skip 4

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:

' keeps
' the
' doctor
' away

SkipWhile

下列程式碼範例使用 Visual Basic 中的 Skip While 子句,以在字串的第一個字母是 "a" 時略過陣列中的字串。 陣列中的其餘字串會予以傳回。


Dim words = {"an", "apple", "a", "day", "keeps", "the", "doctor", "away"}

Dim query = From word In words
            Skip While word.Substring(0, 1) = "a"

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:

' day
' keeps
' the
' doctor
' away

Take

下列程式碼範例使用 Visual Basic 中的 Take 子句,以傳回字串陣列中的前兩個字串。


Dim words = {"an", "apple", "a", "day", "keeps", "the", "doctor", "away"}

Dim query = From word In words
            Take 2

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:

' an
' apple

TakeWhile

下列程式碼範例使用 Visual Basic 中的 Take While 子句,以在字串長度等於或小於五時傳回陣列中的字串。


Dim words = {"an", "apple", "a", "day", "keeps", "the", "doctor", "away"}

Dim query = From word In words
            Take While word.Length < 6

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:

' an
' apple
' a
' day
' keeps
' the

另請參閱