Vishal
Vishal

Reputation: 12369

How to write a "Not In" SQL query in LINQ?

How would I translate the following SQL query in to a comparable LINQ query?

select * from Dept 
where Id not in (
    Select Id 
    from Employee 
    where Salary > 100);

Upvotes: 8

Views: 1279

Answers (2)

Rob
Rob

Reputation: 21

How about this?

var lowPaidEmps = from d in db.Dept 
                  join e in db.Employees on d.Id equals e.Id 
                  where e.Salary <= 100
                  select d;

Upvotes: 0

Andrew Hare
Andrew Hare

Reputation: 351466

Try something like this:

var result = from d in Dept
             let expensiveEmployeeIds = (from e in Employee.Employees
                                       where e.Salary > 100
                                       select e.Id)
             where !expensiveEmployeeIds.Contains(d.Id)
             select d;

Upvotes: 15

Related Questions