数据分区

更新:2007 年 11 月

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

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

LINQ 分区操作

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

运算符

运算符名称

说明

C# 查询表达式语法

Visual Basic 查询表达式语法

更多信息

Skip

跳过序列中的指定位置之前的元素。

不适用。

Skip

Enumerable.Skip<TSource>

Queryable.Skip<TSource>

SkipWhile

基于谓词函数跳过元素,直到某元素不再满足条件。

不适用。

Skip While

Enumerable.SkipWhile

Queryable.SkipWhile

Take

提取序列中的指定位置之前的元素。

不适用。

Take

Enumerable.Take<TSource>

Queryable.Take<TSource>

TakeWhile

基于谓词函数提取元素,直到某元素不再满足条件。

不适用。

Take While

Enumerable.TakeWhile

Queryable.TakeWhile

查询表达式语法示例

Skip

下面的代码示例在 Visual Basic 中使用 Skip 子句来跳过字符串数组中的前四个字符串,然后返回此数组中的剩余字符串。

Dim words() As String = New String() {"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() As String = New String() {"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() As String = New String() {"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() As String = New String() {"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

请参见

概念

标准查询运算符概述

参考

Skip 子句 (Visual Basic)

Skip While 子句 (Visual Basic)

Take 子句 (Visual Basic)

Take While 子句 (Visual Basic)

System.Linq