LINQ 中的分区是指将输入序列划分为两个部分的作,而无需重新排列元素,然后返回其中一个部分。
下图显示了对一系列字符执行三种不同的分区作的结果。 第一个操作返回序列中的前三个元素。 第二个作跳过前三个元素并返回其余元素。 第三个作跳过序列中的前两个元素,并返回接下来的三个元素。
以下部分列出了用于分割序列的标准查询操作符方法。
运营商
操作员名称 | DESCRIPTION | 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 |
查询表达式语法示例
跳过
下面的代码示例使用 Skip
Visual Basic 中的子句跳过字符串数组中的前四个字符串,然后再返回数组中的剩余字符串。
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
下面的代码示例使用 Skip While
Visual Basic 中的子句跳过数组中的字符串,而字符串的第一个字母为“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 中的子句从数组返回字符串,而字符串的长度为 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