确定序列中任何或所有元素是否满足某一条件

如果序列中的所有元素都满足某一项条件,则 All 运算符会返回 true

如果序列中的任意一个元素满足某一项条件,则 Any 运算符会返回 true

示例 1

下面的示例返回由至少下了一个订单的客户组成的序列。 如果给定的 Customer 有任何 Order,则 Where/where 子句的计算结果为 true

var OrdersQuery =
    from cust in db.Customers
    where cust.Orders.Any()
    select cust;
Dim OrdersQuery = _
    From cust In db.Customers _
    Where cust.Orders.Any() _
    Select cust

示例 2

下面的 Visual Basic 代码确定未下订单的客户的列表,并确保对于该列表中的每一位客户,都提供了联系人名称。

Public Sub ContactsAvailable()
    Dim db As New Northwnd("c:\northwnd.mdf")
    Dim result = _
        (From cust In db.Customers _
         Where Not cust.Orders.Any() _
         Select cust).All(AddressOf ContactAvailable)

    If result Then
        Console.WriteLine _
    ("All of the customers who have made no orders have a contact name")
    Else
        Console.WriteLine _
    ("Some customers who have made no orders have no contact name")
    End If
End Sub

Function ContactAvailable(ByVal contact As Object) As Boolean
    Dim cust As Customer = CType(contact, Customer)
    Return (cust.ContactTitle Is Nothing OrElse _
        cust.ContactTitle.Trim().Length = 0)
End Function

示例 3

下面的 C# 示例返回由订单包含以“C”开头的 ShipCity 的客户组成的序列。 返回结果中还包括未下订单的客户。 (根据设计,All 运算符为空序列返回 true。)通过使用 Count 运算符在控制台输出中消除了未下订单的客户。

var custEmpQuery =
    from cust in db.Customers
    where cust.Orders.All(o => o.ShipCity.StartsWith("C"))
    orderby cust.CustomerID
    select cust;

foreach (Customer custObj in custEmpQuery)
{
    if (custObj.Orders.Count > 0)
        Console.WriteLine("CustomerID: {0}", custObj.CustomerID);
    foreach (Order ordObj in custObj.Orders)
    {
        Console.WriteLine("\t OrderID: {0}; ShipCity: {1}",
            ordObj.OrderID, ordObj.ShipCity);
    }
}

请参阅