简体   繁体   中英

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?

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),
       });

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) };

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