简体   繁体   中英

LINQ: List all when count in join table equals zero

Currently I have two tables

1) A list of "jobs"

+--------+-------------+
| job_id | job_name    |
+--------+-------------+
| 1234   | Test Job #1 |
| 5678   | Test Job #2 |
| 9101   | Test Job #3 |
| 1475   | Test Job #4 |
+--------+-------------+

2) A list of "invoices" that relate to each job

| invoice_id    | job_id    | invoice_amount
| 1             | 1234      | 950
| 2             | 1234      | 120
| 3             | 5678      | 560

I need to find a way to select all the "jobs" where they do not have an "invoice" - so ultimately the expected result would be:

| job_id    | job_name      |
| 9101      | Test Job #3   | 
| 1475      | Test Job #4   | 

I'm trying things like:

SELECT *
FROM jobs
WHERE NOT EXISTS (
  SELECT * FROM invoices 
  WHERE jobs.job_id = invoices.invoice_id
)

And still no luck. How can this be achieved in LINQ? Any help is much appreciated!

Linq

var results = (from job in jobs
              join invoice in invoices on job.job_id equals invoice.job_id into total
              from record in total.DefaultIfEmpty()
              where record == null
              select job).ToList();

Method Syntax

GroupJoin is little tricky and comes handy at the same time.

This table expains how GroupJoin works. (Note: observe usage of k and g in code)

|   Job Records (k)    |Invoice Records (g) |
+----------------------+--------------------+
| 1234   | Test Job #1 |{2 matching records}|
| 5678   | Test Job #2 |{1 matching record} |
| 9101   | Test Job #3 |{0 matching records}|
| 1475   | Test Job #4 |{0 matching records}|  

Final code

 var result = jobs.GroupJoin(invoices,r=>r.job_id,c=>c.invoice_id,
                                (k,g) => new {k,g})
                                .Where(x=>x.g.Count()==0)
                                .Select(s=> new {s.k.job_id,s.k.job_name}).ToList();

You can use an inner select:

SELECT * FROM jobs
WHERE job_id NOT IN (SELECT job_id FROM invoices);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM