Επεξεργασία

Κοινή χρήση μέσω


Take Clause (Visual Basic)

Returns a specified number of contiguous elements from the start of a collection.

Syntax

Take count  

Parts

count
Required. A value or an expression that evaluates to the number of elements of the sequence to return.

Remarks

The Take clause causes a query to include a specified number of contiguous elements from the start of a results list. The number of elements to include is specified by the count parameter.

You can use the Take clause with the Skip clause to return a range of data from any segment of a query. To do this, pass the index of the first element of the range to the Skip clause and the size of the range to the Take clause. In this case, the Take clause must be specified after the Skip clause.

When you use the Take clause in a query, you may also need to ensure that the results are returned in an order that will enable the Take clause to include the intended results. For more information about ordering query results, see Order By Clause.

You can use the TakeWhile clause to specify that only certain elements be returned, depending on a supplied condition.

Example

The following code example uses the Take clause together with the Skip clause to return data from a query in pages. The GetCustomers function uses the Skip clause to bypass the customers in the list until the supplied starting index value, and uses the Take clause to return a page of customers starting from that index value.

Public Sub PagingSample()
    Dim pageNumber As Integer = 0
    Dim pageSize As Integer = 10

    Dim customersPage = GetCustomers(pageNumber * pageSize, pageSize)

    Do While customersPage IsNot Nothing
        Console.WriteLine(vbCrLf & "Page: " & pageNumber + 1 & vbCrLf)

        For Each cust In customersPage
            Console.WriteLine(cust.CustomerID & ", " & cust.CompanyName)
        Next

        Console.WriteLine(vbCrLf)

        pageNumber += 1
        customersPage = GetCustomers(pageNumber * pageSize, pageSize)
    Loop
End Sub

Public Function GetCustomers(ByVal startIndex As Integer,
                             ByVal pageSize As Integer) As List(Of Customer)

    Dim customers = GetCustomerList()

    Dim returnCustomers = From cust In customers
                          Skip startIndex Take pageSize

    If returnCustomers.Count = 0 Then Return Nothing

    Return returnCustomers
End Function

See also