Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to do an outer join in LINQ?

I have defined two entities that map to two tables in my database. In SQL I would do a join like this:

select *
from tableA a
left outer join tableB b on b.ID = a.ID
where some condition

How might I do this with a LINQ query?

like image 557
Chev Avatar asked Dec 03 '25 21:12

Chev


2 Answers

Using Labda Expressions you use a GroupJoin

Example:

var query =
  People
  .GroupJoin(
    Pets,
    person => person.PersonId,
    pet => per.Owner,
    (person, petCollection) =>
       new
       {
          Person = person,
          Pets = petCollection.Select(pet => pet.Name),
       });
like image 59
DaveShaw Avatar answered Dec 06 '25 13:12

DaveShaw


See: How to: Perform Left Outer Joins (C# Programming Guide) on MSDN.

For example:

var query = from person in people
    join pet in pets on person equals pet.Owner into gj
    from subpet in gj.DefaultIfEmpty()
    select new { person.FirstName, PetName = (subpet == null ? String.Empty : subpet.Name) };
like image 20
Kieren Johnstone Avatar answered Dec 06 '25 11:12

Kieren Johnstone



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!