指定查询的筛选条件。
语法
Where condition
部件
condition
必填。 一个表达式,用于确定集合中当前项的值是否包含在输出集合中。 表达式的计算结果必须为值 Boolean
或值等效的值 Boolean
。 如果条件的计算结果 True
为,则元素包含在查询结果中;否则,该元素将从查询结果中排除。
注解
该 Where
子句允许你仅选择满足特定条件的元素来筛选查询数据。 导致 Where
子句计算 True
结果中包含的元素;排除其他元素。 子句中使用的 Where
表达式必须计算结果为 a Boolean
或等效项 Boolean
,例如计算结果为 0 时的 Integer False
。 可以使用逻辑运算符(例如And
,、、Or
AndAlso
、OrElse
和IsNot
Is
)在子句中Where
组合多个表达式。
默认情况下,在访问查询表达式之前不会计算查询表达式,例如,当查询表达式被数据绑定或循环访问时 For
。 因此, Where
在访问查询之前,不会计算子句。 如果在子句中使用的 Where
查询外部有值,请确保在执行查询时在 Where
子句中使用适当的值。 有关查询执行的详细信息,请参阅 编写第一个 LINQ 查询。
可以调用子句中的 Where
函数,对集合中当前元素的值执行计算或作。 在子句中 Where
调用函数可能会导致在定义查询时立即执行,而不是在访问查询时执行。 有关查询执行的详细信息,请参阅 编写第一个 LINQ 查询。
示例 1
以下查询表达式使用子From
句为集合中的每个cust
对象声明范围变量Customer
customers
。 子 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
示例 2
以下示例在子句中使用And
Where
和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