LINQ 中的量词运算
这些运算符返回布尔值,即如果序列中的某些或所有元素满足特定条件,则返回 True 或 False。
运算符 | 说明 | C# 查询表达式语法 | VB 查询表达式语法 |
---|---|---|---|
All | 如果序列的所有元素都满足谓词条件,则返回值为“True” | 不适用 | Aggregate … In … Into All(…) |
Any | 通过搜索序列来确定同一序列中是否任何元素满足指定条件 | 不适用 | Aggregate … In … Into Any() |
Contains | 如果在序列中找到特定元素,则返回“True”值;如果序列不包含该特定元素,则返回“false”值 | 不适用 | 不适用 |
All 的示例 - All(Of TSource) 扩展方法
VB
Module Module1 Sub Main() 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}} 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 For Each e In query Console.WriteLine("Name = {0}", e) Next Console.WriteLine(vbLf & "Press any key to continue.") Console.ReadKey() End Sub 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 End Module
当编译并执行 VB 中的上述代码时,会生成以下结果 −
Arlene Rui Press any key to continue.
Any 的示例 - 扩展方法
VB
Module Module1 Sub Main() 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}} 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 For Each e In query Console.WriteLine("Name = {0}", e) Next Console.WriteLine(vbLf & "Press any key to continue.") Console.ReadKey() End Sub 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 End Module
当编译并执行 VB 中的上述代码时,会生成以下结果 −
Rui Press any key to continue.
linq_query_operators.htm
广告