开发者

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 co开发者_Go百科ndition

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜