Any
说明:用于判断集合中是否有元素满足某一条件;不延迟。(若条件为空,则集合只要不为空就返回True,否则为False)。
1.简单形式:
仅返回没有订单的客户:
var q =
from c in db.Customers
where !c.Orders.Any()
select c;
生成SQL语句为:
SELECT [t0].[CustomerID], [t0].[CompanyName], [t0].[ContactName],
[t0].[ContactTitle], [t0].[Address], [t0].[City], [t0].[Region],
[t0].[PostalCode], [t0].[Country], [t0].[Phone], [t0].[Fax]
FROM [dbo].[Customers] AS [t0]
WHERE NOT (EXISTS(
SELECT NULL AS [EMPTY] FROM [dbo].[Orders] AS [t1]
WHERE [t1].[CustomerID] = [t0].[CustomerID]
))
All
说明:用于判断集合中所有元素是否都满足某一条件;不延迟
var q =
from c in db.Customers
where c.Orders.All(o => o.ShipCity == c.City)
select c;
语句描述:这个例子返回所有订单都运往其所在城市的客户或未下订单的客户。
------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
注意Any 和 All
var list = new List<int>();
var aa = list.All(n => n > 1);
var bb = list.Any(n => n > 1);
// aa: true bb: false
看看他生成的SQL,我们就知道原因了
All: IQueryable<Test>.All(t=>t.OpenId=="")
-- Region Parameters
DECLARE @p0 NVarChar(1000) = ''
-- EndRegion
SELECT
(CASE
WHEN NOT (EXISTS(
SELECT NULL AS [EMPTY]
FROM [Test] AS [t1]
WHERE (
(CASE
WHEN [t1].[OpenId] = @p0 THEN 1
ELSE 0
END)) = 0
)) THEN 1
WHEN NOT NOT (EXISTS(
SELECT NULL AS [EMPTY]
FROM [Test] AS [t1]
WHERE (
(CASE
WHEN [t1].[OpenId] = @p0 THEN 1
ELSE 0
END)) = 0
)) THEN 0
ELSE NULL
END) AS [value]
可以看得出来, All 是用的 Not (Exists) , 当Query为空的时候,Exists是为false的,而前面一个Not (false),当然也成为了True;
Any: IQueryable<Test>.Any(t=>t.OpenId=="")
DECLARE @p0 NVarChar(1000) = ''
-- EndRegion
SELECT
(CASE
WHEN EXISTS(
SELECT NULL AS [EMPTY]
FROM [Test] AS [t0]
WHERE [t0].[OpenId] = @p0
) THEN 1
ELSE 0
END) AS [value]
可以看出 Any生成的是Exists。 当Query为空的时候,Exists是为false的。