LINQ

算算時間,接觸LINQ也有一個月的時間了,可以算是落伍兼新生,不過最近在寫專案的時候,遇到了在LINQ的Where條件式中要如何使用in與 not in呢!? 這時候真的只能坐在位子上仰天長笑,開始懷念T-SQL其實你還是最好用滴。之後,為了讓自己日後開發時更為方便,於是花了一點時間,參考一些網路資料及 MSDN後,得到以下的測試結果:(以下以北風資料庫為範本)
T-SQL的IN:
Select ProductID, ProductName, CategoryID From dbo.Products 
Where not CategoryID in (1, 2)

T-SQL的NOT IN:
Select ProductID, ProductName, CategoryID From dbo.Products 
Where CategoryID not in (1, 2)
or
Select ProductID, ProductName, CategoryID From dbo.Products 
Where not CategoryID in (1, 2)

LINQ的IN:
var queryResult = from p in db.Products
where (new int?[] {1,2}).Contains(p.CategoryID)
select p;

LINQ的IN解析成SQL:
SELECT [t0].[ProductID], [t0].[ProductName], [t0].[SupplierID], [t0].[CategoryID], [t0].[QuantityPerUnit], [t0].[UnitPrice], [t0].[UnitsInStock], [t0].[UnitsOnOrder], [t0].[ReorderLevel], [t0].[Discontinued]
FROM [dbo].[Products] AS [t0]
WHERE [t0].[CategoryID] IN (@p0, @p1)

LINQ的NOT IN:
var queryResult = from p in db.Products
where !(new int?[] { 1, 2 }).Contains(p.CategoryID)
select p;

LINQ的NOT IN解析成SQL:
SELECT [t0].[ProductID], [t0].[ProductName], [t0].[SupplierID], [t0].[CategoryID], [t0].[QuantityPerUnit], [t0].[UnitPrice], [t0].[UnitsInStock], [t0].[UnitsOnOrder], [t0].[ReorderLevel], [t0].[Discontinued]
FROM [dbo].[Products] AS [t0]
WHERE NOT ([t0].[CategoryID] IN (@p0, @p1))

原文地址:https://www.cnblogs.com/sandea/p/3289911.html