使用“NOT IN”的 LINQ to SQL 查询
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/344478/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
LINQ to SQL query using "NOT IN"
提问by jinsungy
Can LINQ to SQL query using NOT IN?
可以使用NOT IN 进行LINQ to SQL 查询吗?
e.g., SELECT au_lname, state FROM authors WHERE state NOT IN ('CA', 'IN', 'MD')
例如,SELECT au_lname, state FROM author WHERE state NOT IN ('CA', 'IN', 'MD')
回答by tvanfosson
List<string> states = new List<string> { "CA", "IN", "MD" };
var q = from a in authors
where !states.Contains(a.state)
select new { a.au_lname, a.state };
or
或者
var q = authors.Where( a => !states.Contains( a.state ) )
.Select( a => new { a.au_lname, a.state } );
回答by CMS
You can do it with Contains:
您可以使用“包含”来做到这一点:
var states = new[] {"CA", "IN", "MD"};
var query = db.Authors.Where(x => !states.Contains(x.state));
回答by Galwegian
here's an example:
这是一个例子:
NorthwindDataContext dc = new NorthwindDataContext();
dc.Log = Console.Out;
var query =
from c in dc.Customers
where !(from o in dc.Orders
select o.CustomerID)
.Contains(c.CustomerID)
select c;
foreach (var c in query) Console.WriteLine( c );
回答by Rob
Yes!
是的!
Here's an example from code we already had written:
这是我们已经编写的代码中的一个示例:
List<long> badUserIDs = new List { 10039309, 38300590, 500170561 };
BTDataContext dc = new BTDataContext();
var items = from u in dc.Users
where !badUserIDs.Contains(u.FbUserID)
select u;
The generated SQL turns out to be:
结果生成的 SQL 是:
{SELECT [t0].[UserID], [t0].[FbUserID], [t0].[FbNetworkID], [t0].[Name],
FROM [dbo].[Users] AS [t0]
WHERE NOT ([t0].[FbUserID] IN (@p0, @p1, @p2))
}
{SELECT [t0].[UserID], [t0].[FbUserID], [t0].[FbNetworkID], [t0].[Name],
FROM [dbo].[Users] AS [t0]
WHERE NOT ([t0].[FbUserID] IN (@p0, @p1, @p2))
}