判斷序列中的任何或所有項目是否全都符合條件
如果序列中所有的項目都符合條件,則 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);
}
}