LINQ to SQL语句(7)之Exists/In/Any/All/Contains
系列文章导航:
LINQ to SQL语句(2)之Select/Distinct
LINQ to SQL语句(3)之Count/Sum/Min/Max/Avg
LINQ to SQL语句(6)之Group By/Having
LINQ to SQL语句(7)之Exists/In/Any/All/Contains
LINQ to SQL语句(8)之Concat/Union/Intersect/Except
LINQ to SQL语句(9)之Top/Bottom和Paging和SqlMethods
LINQ to SQL语句(12)之Delete和使用Attach
LINQ to SQL语句(14)之Null语义和DateTime
LINQ to SQL语句(19)之ADO.NET与LINQ to SQL
Exists/In/Any/All/Contains操作符
适用场景:用于判断集合中元素,进一步缩小范围。
Any
说明:用于判断集合中是否有元素满足某一条件;不延迟。(若条件为空,则集合只要不为空就返回True,否则为False)。有2种形式,分别为简单形式和带条件形式。
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] ))
2.带条件形式:
仅返回至少有一种产品断货的类别:
var q = from c in db.Categories where c.Products.Any(p => p.Discontinued) select c;
生成SQL语句为:
SELECT [t0].[CategoryID], [t0].[CategoryName], [t0].[Description], [t0].[Picture] FROM [dbo].[Categories] AS [t0] WHERE EXISTS( SELECT NULL AS [EMPTY] FROM [dbo].[Products] AS [t1] WHERE ([t1].[Discontinued] = 1) AND ([t1].[CategoryID] = [t0].[CategoryID]) )