Niklas
Niklas

Reputation: 13145

How do I specify "not in" in this lambda expression?

I have a quick question becuase my brain won't work with me...
Where do I specify that I want the user_id's in 'Users' that are NOT in 'Groups' ?

db.Users.Join(db.Groups, a => a.user_id, b => b.user_id, (a, b) => new SelectListItem
{
  Value = a.user_id.ToString(),
  Text = a.surname + " " + a.lastname
});

Upvotes: 6

Views: 8090

Answers (2)

Felipe Oriani
Felipe Oriani

Reputation: 38608

you can try something like this:

var query =  from u in db.Users
             where !(from g in dc.Groups
                     select g.user_id)
                     .Contains(u.user_id)
             select new SelectListItem { 
                         Value = u.user_id.ToString(),
                     Text = u.surname + " " + u.lastname
         };

Take a look here: http://introducinglinq.com/blogs/marcorusso/archive/2008/01/14/the-not-in-clause-in-linq-to-sql.aspx

Upvotes: 0

Nuffin
Nuffin

Reputation: 3972

The following should work (assuming that I understood your question correctly):

db.Users
.Where(x => !db.Groups.Any(y => y.user_id == x.user_id))
.Select(a => new SelectListItem
    {
        Value = a.user_id.ToString(),
        Text = a.surname + " " + a.lastname
    });

Upvotes: 13

Related Questions