29

Can LINQ to SQL query using NOT IN?

e.g., SELECT au_lname, state FROM authors WHERE state NOT IN ('CA', 'IN', 'MD')

4 Answers 4

51
    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 } );
Sign up to request clarification or add additional context in comments.

Comments

9

You can do it with Contains:

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

Comments

7

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

1 Comment

There's not really need to do the subquery - the Contains / !Contains will work within the context of the main query.
4

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:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.