Bagikan melalui


How to: Determine if Any or All Elements in a Sequence Satisfy a Condition (LINQ to SQL)

The All<TSource> operator returns true if all elements in a sequence satisfy a condition.

The Any operator returns true if any element in a sequence satisfies a condition.

Example

The following example returns a sequence of customers that have at least one order. The Where/where clause evaluates to true if the given Customer has any Order.

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

The following Visual Basic code determines the list of customers who have not placed orders, and ensures that for every customer in that list, a contact name is provided.

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

The following C# example returns a sequence of customers whose orders have a ShipCity beginning with "C". Also included in the return are customers who have no orders. (By design, the All<TSource> operator returns true for an empty sequence.) Customers with no orders are eliminated in the console output by using the Count operator.

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);
    }
}

See Also

Other Resources

Query Examples (LINQ to SQL)