LINQ to SQL查询使用“NOT IN”

时间:2008-12-05 16:52:53

标签: sql .net linq linq-to-sql

可以使用 NOT IN 进行LINQ to SQL查询吗?

例如,SELECT au_lname,state FROM authors WHERE state NOT IN('CA','IN','MD')

4 个答案:

答案 0 :(得分:48)

    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 };

   var q = authors.Where( a => !states.Contains( a.state ) )
                  .Select( a => new { a.au_lname, a.state } );

答案 1 :(得分:9)

你可以用Contains:

来做
       var states = new[]  {"CA", "IN", "MD"};
       var query = db.Authors.Where(x => !states.Contains(x.state));

答案 2 :(得分:6)

这是一个例子:

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 );

答案 3 :(得分:4)

是的!

以下是我们已编写的代码示例:


            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;

生成的SQL原来是:

{SELECT [t0].[UserID], [t0].[FbUserID], [t0].[FbNetworkID], [t0].[Name], FROM [dbo].[Users] AS [t0] WHERE NOT ([t0].[FbUserID] IN (@p0, @p1, @p2)) }