接觸 LINQ 也有很長的一段時間了,有些在 SQL 語句中用的很順手的東西在 Linq 中卻不知道如何實現了,最近遇到了一個問題,在 LINQ 的 Where 條件式中要如何使用 IN 與 NOT IN 呢? 這時候真的開始懷念 T-SQL 其實還是最好用的。為了讓自己日后開發時更為方便,於是花了一點時間,參考一些網絡資料及 MSDN 后,得到以下的測試結果:
T-SQL的IN:
Select ProductID, ProductName, CategoryIDFrom dbo.ProductsWhere CategoryID in (1, 2)
T-SQL的NOT IN:
Select ProductID, ProductName, CategoryIDFrom dbo.ProductsWhere CategoryID not in (1, 2)
Or
Select ProductID, ProductName, CategoryIDFrom dbo.ProductsWhere not CategoryID in (1, 2)
LINQ的IN:
var queryResult = from p in db.Productswhere (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.Productswhere ! (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)
轉自:http://blog.csdn.net/zhangyumei/article/details/5620363
