LINQ 中的分区运算符



将输入序列划分为两个独立的部分,不重新排列序列的元素,然后返回其中一个部分。

运算符 描述 C# 查询表达式语法 VB 查询表达式语法
Skip 跳过序列中指定的某些数量的元素,并返回剩下的元素 不可用 Skip
SkipWhile 如 Skip 相同,唯一的例外是跳过的元素数量由布尔条件指定 不可用 Skip While
Take 从序列中获取指定数量的元素,并跳过剩下的元素 不可用 Take
TakeWhile 如 Take 相同,但所取元素数量由布尔条件指定 不可用 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
linq_query_operators.htm
Advertisement
© . All rights reserved.