LINQ 中的數據分割是指將輸入序列分割成兩個區段的作業,而不重新排列元素,然後傳回其中一個區段。
以下圖示顯示字元序列上三個不同分割操作的結果。 第一個操作會傳回序列中的前三個元素。 第二個作業會略過前三個元素,並傳回其餘元素。 第三個操作會略過序列中的前兩個元素,並回傳接下來的三個元素。
分割順序的標準查詢運算符方法會列在下一節中。
運營商
| 運算子名稱 | 說明 | Visual Basic 查詢表達式語法 | 詳細資訊 |
|---|---|---|---|
| 跳過 | 跳過序列中的元素直到特定位置。 | Skip |
Enumerable.Skip Queryable.Skip |
| 跳過(SkipWhile) | 略過以述詞函式為基礎的元素,直到元素不符合條件為止。 | Skip While |
Enumerable.SkipWhile Queryable.SkipWhile |
| 拿 | 取用序列中至指定位置的元素。 | 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' 時,略過陣列中以 '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 中的 子句傳回字串陣列中的前兩個字串。
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
下列程式代碼範例會使用 Take While Visual Basic 中的 子句傳回陣列中的字串,而字串的長度為五或更少。
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