Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Left join where right is null

Tags:

c#

linq

I'm trying to left join in c# to find only values from Foo, that aren't in Bar. In SQL I would normally do this:

SELECT * FROM FOO f
LEFT JOIN BAR b ON f.ID = b.ID
WHERE b.ID IS NULL

With linq I normally do something like this:

var matches = Foos.Join(
    Bars,
    foo => foo.ID,
    bar => bar.ID,
    (foo, bar) => foo
).Select(x => x.ID);

and then:

var noMatch = Foos.Where(x => !matches.Contains(x.ID));

Now to the question: Is there a way to achieve this within the .Join() function?

like image 717
Luca Avatar asked Sep 18 '25 19:09

Luca


2 Answers

Does something like this work:

Foos.
.GroupJoin(
    Bars,
    f => f.Id,
    b => b.Id,
    (f, lj) => new { f, lj })
    .SelectMany(t => t.lj.DefaultIfEmpty(),
            (t, b) => new { 
                foo = t.f,
                bar = b
                })
    .Where(a => a.bar.Any() == false)
    .ToList()   
like image 55
sam Avatar answered Sep 21 '25 09:09

sam


You can do a left join as I show below:

var query= from f in Foos
           join b in Bars on f.Id equals b.Id into gb
           from sb in gb.DefaulfIfEmpty()
           where sb.ID==null
           select {f, sb};
like image 21
octavioccl Avatar answered Sep 21 '25 10:09

octavioccl