限定符作返回一个 Boolean 值,该值指示序列中的某些或所有元素是否满足条件。
下图描述了两个不同源序列上的两个不同限定符运算。 第一个操作检查是否有任何元素是字符“A”。 第二个操作是询问所有元素是否都是字符“A”。 这两种方法在此示例中都返回 true
。
以下部分列出了执行限定符作的标准查询运算符方法。
方法
方法名 | DESCRIPTION | Visual Basic 查询表达式语法 | 详细信息 |
---|---|---|---|
全部 | 确定序列中的所有元素是否满足条件。 | Aggregate … In … Into All(…) |
Enumerable.All Queryable.All |
任意 | 确定序列中的任何元素是否满足条件。 | Aggregate … In … Into Any() |
Enumerable.Any Queryable.Any |
包含 | 确定序列是否包含指定的元素。 | 不適用。 | Enumerable.Contains Queryable.Contains |
查询表达式语法示例
这些示例使用 Aggregate
Visual Basic 中的子句作为 LINQ 查询中筛选条件的一部分。
下面的示例使用 Aggregate
子句和 All 扩展方法从集合中返回其宠物都超过指定年龄的人员。
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