Where 子句 (Visual Basic)

指定查询的筛选条件。

Where condition

部件

  • condition
    必选。 一个表达式,确定是否在输出集合中包含集合中当前项的值。 该表达式的计算结果必须为 Boolean 值或 Boolean 值的等效值。 如果条件的计算结果为 True,则在查询结果中包含该元素;否则从查询结果中排除该元素。

备注

使用 Where 子句,可以通过仅选择满足特定条件的元素来筛选查询数据。 其值使 Where 子句的计算结果为 True 的元素将包含在查询结果中;其他元素将被排除。 Where 子句中使用的表达式的计算结果必须为 Boolean 值或 Boolean 值的等效值(例如 Integer 值 — 当其值为 0 时,计算结果为 False)。 使用逻辑运算符(如 And、Or、AndAlso、OrElse、Is 和 IsNot)可以将多个表达式组合在一个 Where 子句中。

默认情况下,查询表达式直到被访问时(例如,当它们进行数据绑定或在 For 循环中进行循环访问时)才计算结果。 因此,在访问查询前,不会计算 Where 子句。 如果值位于 Where 子句中使用的查询外部,请确保查询执行时在 Where 子句中使用适当的值。 有关查询执行的更多信息,请参见编写第一个 LINQ 查询 (Visual Basic)

您可以在 Where 子句中调用函数,以便对集合中当前元素的值执行计算或运算。 在 Where 子句中调用函数可使查询在定义后立即执行,而不是在访问时执行。 有关查询执行的更多信息,请参见编写第一个 LINQ 查询 (Visual Basic)

示例

下面的查询表达式使用 From 子句为 customers 集合中的每个 Customer 对象声明范围变量 cust。 Where 子句使用范围变量将输出限制为指定地区的客户。 For Each 循环在查询结果中显示每个客户的公司名称。

Sub DisplayCustomersForRegion(ByVal customers As List(Of Customer),
                              ByVal region As String)

  Dim customersForRegion = From cust In customers
                           Where cust.Region = region

  For Each cust In customersForRegion
    Console.WriteLine(cust.CompanyName)
  Next
End Sub

下面的示例在 Where 子句使用 And 和 Or 逻辑运算符。

Private Sub DisplayElements()
    Dim elements As List(Of Element) = BuildList()

    ' Get a list of elements that have an atomic number from 12 to 14,
    ' or that have a name that ends in "r".
    Dim subset = From theElement In elements
        Where (theElement.AtomicNumber >= 12 And theElement.AtomicNumber < 15) _
        Or theElement.Name.EndsWith("r")
        Order By theElement.Name

    For Each theElement In subset
        Console.WriteLine(theElement.Name & " " & theElement.AtomicNumber)
    Next

    ' Output:
    '  Aluminum 13
    '  Magnesium 12
    '  Silicon 14
    '  Sulfur 16
End Sub

Private Function BuildList() As List(Of Element)
    Return New List(Of Element) From
        {
            {New Element With {.Name = "Sodium", .AtomicNumber = 11}},
            {New Element With {.Name = "Magnesium", .AtomicNumber = 12}},
            {New Element With {.Name = "Aluminum", .AtomicNumber = 13}},
            {New Element With {.Name = "Silicon", .AtomicNumber = 14}},
            {New Element With {.Name = "Phosphorous", .AtomicNumber = 15}},
            {New Element With {.Name = "Sulfur", .AtomicNumber = 16}}
        }
End Function

Public Class Element
    Public Property Name As String
    Public Property AtomicNumber As Integer
End Class

请参见

参考

From 子句 (Visual Basic)

Select 子句 (Visual Basic)

For Each...Next 语句 (Visual Basic)

概念

Visual Basic 中的 LINQ 简介

其他资源

查询 (Visual Basic)