數量詞作業
數量詞作業會傳回 Boolean 值,指出序列中的部分或所有項目是否都符合條件。
下圖說明對兩個不同來源序列執行的兩個不同數量詞作業。 第一個作業會問是否有一個或多個項目為字元 'A',而結果是 true。 第二個作業會問是否所有項目都是字元 'A',而結果是 true。
下節會列出執行數量詞作業的標準查詢運算子方法。
方法
方法名稱 |
描述 |
C# 查詢運算式語法 |
Visual Basic 查詢運算式語法 |
詳細資訊 |
---|---|---|---|---|
全部 |
判斷序列中的項目是否全都符合條件。 |
不適用。 |
Aggregate … In … Into All(…) |
|
Any |
判斷序列中是否有任何項目會符合條件。 |
不適用。 |
Aggregate … In … Into Any() |
|
包含 |
判斷序列是否包含指定的項目。 |
不適用。 |
不適用。 |
查詢運算式語法範例
這些範例在 Visual Basic 中使用 Aggregate 子句,做為 LINQ 查詢中篩選條件的一部分。
下列範例使用 Aggregate 子句和 All<TSource> 擴充方法,以傳回集合中寵物年齡全都大於所指定年齡的人。
Class Person
Public Property Name As String
Public Property Pets As Pet()
End Class
Class Pet
Public Property Name As String
Public Property Age As Integer
End Class
Sub All()
Dim barley As New Pet With {.Name = "Barley", .Age = 4}
Dim boots As New Pet With {.Name = "Boots", .Age = 1}
Dim whiskers As New Pet With {.Name = "Whiskers", .Age = 6}
Dim bluemoon As New Pet With {.Name = "Blue Moon", .Age = 9}
Dim daisy As New Pet With {.Name = "Daisy", .Age = 3}
Dim charlotte As New Person With {.Name = "Charlotte", .Pets = New Pet() {barley, boots}}
Dim arlene As New Person With {.Name = "Arlene", .Pets = New Pet() {whiskers}}
Dim rui As New Person With {.Name = "Rui", .Pets = New Pet() {bluemoon, daisy}}
' Create the list of Person objects that will be queried.
Dim people As New System.Collections.Generic.List(Of Person)(New Person() {charlotte, arlene, rui})
Dim query = From pers In people
Where (Aggregate pt In pers.Pets Into All(pt.Age > 2))
Select pers.Name
Dim sb As New System.Text.StringBuilder()
For Each name As String In query
sb.AppendLine(name)
Next
' Display the results.
MsgBox(sb.ToString())
' This code produces the following output:
' Arlene
' Rui
End Sub
下一個範例使用 Aggregate 子句和 Any 擴充方法,以傳回集合中至少有一隻寵物年齡大於所指定年齡的人。
Class Person
Public Property Name As String
Public Property Pets As Pet()
End Class
Class Pet
Public Property Name As String
Public Property Age As Integer
End Class
Sub Any()
Dim barley As New Pet With {.Name = "Barley", .Age = 4}
Dim boots As New Pet With {.Name = "Boots", .Age = 1}
Dim whiskers As New Pet With {.Name = "Whiskers", .Age = 6}
Dim bluemoon As New Pet With {.Name = "Blue Moon", .Age = 9}
Dim daisy As New Pet With {.Name = "Daisy", .Age = 3}
Dim charlotte As New Person With {.Name = "Charlotte", .Pets = New Pet() {barley, boots}}
Dim arlene As New Person With {.Name = "Arlene", .Pets = New Pet() {whiskers}}
Dim rui As New Person With {.Name = "Rui", .Pets = New Pet() {bluemoon, daisy}}
' Create the list of Person objects that will be queried.
Dim people As New System.Collections.Generic.List(Of Person)(New Person() {charlotte, arlene, rui})
Dim query = From pers In people
Where (Aggregate pt In pers.Pets Into Any(pt.Age > 7))
Select pers.Name
Dim sb As New System.Text.StringBuilder()
For Each name As String In query
sb.AppendLine(name)
Next
' Display the results.
MsgBox(sb.ToString())
' This code produces the following output:
' Rui
End Sub
請參閱
工作
HOW TO:在執行階段動態指定述詞篩選條件 (C# 程式設計手冊)