LINQ分割區操作符


把輸入序列分為兩個獨立的部分,而不重新排列序列中的元素,然後返回其中一個。

操作符 描述 C#查詢表示式語法 VB查詢表示式語法
Skip 跳過一些指定的序列中一些的元素,並返回其餘的 不適用 Skip
SkipWhile 相同,唯一的例外跳到多個元素,跳過的是由一個布林條件指定 不適用 Skip While
Take 採取元素指定數量的序列,並跳過其餘的 不適用 Take
TakeWhile 相同,以不同的事實,即許多元素採取的是由一個布林條件指定 不適用 Take While

Skip例子- 查詢表示式

VB

Module Module1
  Sub Main()
     Dim words = {"once", "upon", "a", "time", "there", "was", "a", "jungle"}

     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)
           Console.WriteLine(str)
        Next
        Console.ReadLine()
  End Sub
End Module

當在VB上述程式碼被編譯和執行時,它產生了以下結果:

there
was
a
jungle

Skip While範例 - 查詢表示式

VB

Module Module1
  Sub Main()
     Dim words = {"once", "upon", "a", "time", "there", "was", "a", "jungle"}

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

     Dim sb As New System.Text.StringBuilder()
        For Each str As String In query
           sb.AppendLine(str)
           Console.WriteLine(str)
        Next 
        Console.ReadLine()
  End Sub
End Module

當在VB上述程式碼被編譯和執行時,它產生了以下結果:

once
upon
a
was
a
jungle

Take例子- 查詢表示式

VB

Module Module1
  Sub Main()
     Dim words = {"once", "upon", "a", "time", "there", "was", "a", "jungle"}

     Dim query = From word In words 
                 Take 3 

     Dim sb As New System.Text.StringBuilder()
        For Each str As String In query
           sb.AppendLine(str)
           Console.WriteLine(str)
        Next 
        Console.ReadLine()
  End Sub
End Module

當在VB上述程式碼被編譯和執行時,它產生了以下結果:

once
upon
a

Take While範例 - 查詢表示式

VB

Module Module1
  Sub Main()
     Dim words = {"once", "upon", "a", "time", "there", "was", "a", "jungle"}

     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)
            Console.WriteLine(str)
        Next 
        Console.ReadLine()
  End Sub
End Module

當在VB上述程式碼被編譯和執行時,它產生了以下結果:

once
upon
a
time
there
was
a