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?
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()
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};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With