Linq 如何实现 in 与 not in

Posted wangfuyou

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Linq 如何实现 in 与 not in相关的知识,希望对你有一定的参考价值。

T-SQL的IN:

Select ProductID, ProductName, CategoryID
From dbo.Products
Where 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://blog.csdn.net/zhangyumei/article/details/5620363

以上是关于Linq 如何实现 in 与 not in的主要内容,如果未能解决你的问题,请参考以下文章

linq not in 查询

linq not in

Linq not in 写法

使用 NOT IN 的 SQL 到 LINQ 转换

LINQ to nHibernate - 将 SQL“NOT IN”表达式转换为 LINQ

LINQ to Entities 中的“NOT IN”子句