"Not In" Clause in Linq to Entities

NOT IN clause in LINQ to Entities

If you are using an in-memory collection as your filter, it's probably best to use the negation of Contains(). Note that this can fail if the list is too long, in which case you will need to choose another strategy (see below for using a strategy for a fully DB-oriented query).

   var exceptionList = new List<string> { "exception1", "exception2" };

var query = myEntities.MyEntity
.Select(e => e.Name)
.Where(e => !exceptionList.Contains(e.Name));

If you're excluding based on another database query using Except might be a better choice. (Here is a link to the supported Set extensions in LINQ to Entities)

   var exceptionList = myEntities.MyOtherEntity
.Select(e => e.Name);

var query = myEntities.MyEntity
.Select(e => e.Name)
.Except(exceptionList);

This assumes a complex entity in which you are excluding certain ones depending some property of another table and want the names of the entities that are not excluded. If you wanted the entire entity, then you'd need to construct the exceptions as instances of the entity class such that they would satisfy the default equality operator (see docs).

Using 'NOT IN' Clause in LINQ Query

You should've done it the other way around. Call Contains() on the subquery, the one that has multiple items in it :

!(from t2 in db.ASN_ITEM
where t2.SCAN_STAT != 2
select t2.AWB_NO
).Distinct()
.Contains(t.AWB_NO)

Also, you have to select AWB_NO directly, as shown above, instead of projecting to anonymous type. Doing the latter will prevent usage of Contains(), since item type in collection will be different from object type passed as parameter of Contains().

How would you do a not in query with LINQ?

I don't know if this will help you but..

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

from The NOT IN clause in LINQ to SQL by Marco Russo

Using Linq to Entities and havign a NOT IN clause

You cannot compile second query, because Except should be used on Queryables of same type. But you are trying to apply it on Queryable<TABLE1> and Queryable<TypeOfTABLE2Key_Value>. Also I think you should use Contains here:

var keys = from pkcr in this.Repository.Context.TABLE2 
where pkcr.Reference_RTK == "FOO"
select pkcr.Key_Value;

var query = from pl in this.Repository.Context.TABLE1
where !keys.Contains(pl.License_RTK)
select pl;

NOTE: Generated query will be NOT EXISTS instead of NOT IN, but that's what you want

SELECT * FROM FROM [dbo].[TABLE1] AS [Extent1]
WHERE NOT EXISTS
(SELECT 1 AS [C1]
FROM [dbo].[TABLE2] AS [Extent2]
WHERE ([Extent2].[Reference_RTK] == @p0) AND
([Extent2].[Key_Value] = [Extent1].[License_RTK]))

NOT IN Condition in Linq

Except expects argument of type IEnumerable<T>, not T, so it should be something like

_empIds = _cmn.GetEmployeeCenterWise(_loggedUserId)                              
.Select(e => e.Id)
.Except(new[] {_loggedUserId})
.ToList();

Also note, this is really redundant in the case when exclusion list contains only one item and can be replaces with something like .Where(x => x != _loggedUserId)

Sql Query with not in clause of subquery to LINQ query

This

    from a in user_user_connection 
join b in user_user_connection on
new {From=a.userid_to, To=a.userid_from} equals new {From=b.userid_from, To=b.userid_to} into c
from d in c.DefaultIfEmpty()
where d == null
select a;

is similar to

select a.*
from user_user_connection a
left join user_user_connection b on a.userid_to = b.userid_from and a.userid_from = b.userid_to
where b.userid_from is null

which should match your not in query.

if you want a specific userid_from you can add another where

    from a in user_user_connection 
where a.userid_from == 3464
join b in user_user_connection on
new {From=a.userid_to, To=a.userid_from} equals new {From=b.userid_from, To=b.userid_to} into c
from d in c.DefaultIfEmpty()
where d == null
select a;

linq to sql where not in

  var friends = (from x in db.FriendsLists
where
(x.TheUser == GlobalVariables.User.ID) ||
(x.TheFriend == GlobalVariables.User.ID)
select x.UserID).ToList();

var notInFriendList = from nf in db.Users
where !friends.Contains(nf.UserID)
select nf;

Linq to Entities - SQL IN clause

You need to turn it on its head in terms of the way you're thinking about it. Instead of doing "in" to find the current item's user rights in a predefined set of applicable user rights, you're asking a predefined set of user rights if it contains the current item's applicable value. This is exactly the same way you would find an item in a regular list in .NET.

There are two ways of doing this using LINQ, one uses query syntax and the other uses method syntax. Essentially, they are the same and could be used interchangeably depending on your preference:

Query Syntax:

var selected = from u in users
where new[] { "Admin", "User", "Limited" }.Contains(u.User_Rights)
select u

foreach(user u in selected)
{
//Do your stuff on each selected user;
}

Method Syntax:

var selected = users.Where(u => new[] { "Admin", "User", "Limited" }.Contains(u.User_Rights));

foreach(user u in selected)
{
//Do stuff on each selected user;
}

My personal preference in this instance might be method syntax because instead of assigning the variable, I could do the foreach over an anonymous call like this:

foreach(User u in users.Where(u => new [] { "Admin", "User", "Limited" }.Contains(u.User_Rights)))
{
//Do stuff on each selected user;
}

Syntactically this looks more complex, and you have to understand the concept of lambda expressions or delegates to really figure out what's going on, but as you can see, this condenses the code a fair amount.

It all comes down to your coding style and preference - all three of my examples do the same thing slightly differently.

An alternative way doesn't even use LINQ, you can use the same method syntax replacing "where" with "FindAll" and get the same result, which will also work in .NET 2.0:

foreach(User u in users.FindAll(u => new [] { "Admin", "User", "Limited" }.Contains(u.User_Rights)))
{
//Do stuff on each selected user;
}

Select NOT IN clause in Linq to Entities

Like this:

from c in db.Customers
where !db.Products.Any(p => p.ProductID == c.ProductID)
select c;


Related Topics



Leave a reply



Submit