对数据进行分区 (Visual Basic)

LINQ 中的分区是指将输入序列划分为两个部分的操作,无需重新排列元素,然后返回其中一个部分。

下图显示对字符序列进行三种不同的分区操作的结果。 第一个操作返回序列中的前三个元素。 第二个操作跳过前三个元素,返回剩余元素。 第三个操作跳过序列中的前两个元素,返回接下来的三个元素。

Illustration that shows three LINQ partitioning operations.

下面一节列出了对序列进行分区的标准查询运算符方法。

运算符

运算符名称 描述 Visual Basic 查询表达式语法 更多信息
Skip 跳过序列中指定位置之前的元素。 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
Chunk 将序列的元素拆分为指定最大大小的区块。 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 子句,在字符串的长度为 5 或更少时,从数组中返回字符串。


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

另请参阅