指定查詢的篩選條件。
語法
Where condition
組件
condition
必須的。 表達式,決定集合中目前專案的值是否包含在輸出集合中。 表達式必須評估為 Boolean 值或值的對等 Boolean 值。 如果條件評估為 True,則專案會包含在查詢結果中;否則,專案會從查詢結果中排除。
備註
子 Where 句可讓您只選取符合特定準則的元素來篩選查詢數據。 導致 Where 子句評估 True 為 的元素會包含在查詢結果中;排除其他元素。 子句中使用的 Where 運算式必須評估為 Boolean 或的 Boolean對等專案,例如當其值為零時評估 False 為的 Integer。 您可以使用 、、Or、、OrElseAndAlso、 Is和 IsNot等And邏輯運算子,在 子句中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
另請參閱
- Visual Basic LINQ 簡介
- 查詢
- From 子句
- Select 子句
- For Each...Next 語句